Frage

We can write functions in 2 ways:

var v1 = m1('hello'); // error
var v2 = m2('hello'); // OK

var m1 = function(param){ 
    // ... 
    return param; 
}

function m2(param){
    // ...
    return param;
}

var v1 = m1('hello'); // OK
var v2 = m2('hello'); // OK

As I know there is only one difference - time of creation:
m2 in compilation time, so we can use it 'before' declaration - like in my case.
m1 in assignment time (code goes line by line) and we cannot use it before.

Is one more efficient for memory or performance?
In which case is one way more semantic, in which case second?
Is here next difference?
When we should use first and when second one?

.

// edit really primitive perf test - same results
// http://jsperf.com/performance-function-writing-way

War es hilfreich?

Lösung

var m1 = function(param){ // ... return param; }

it may make more sense when you consider that a function is an object, and we're just assigning a name to the object. Think of it as saying var m1=[1,2,3]; The content of functions declared this way is also compiled.

When assigning a function like this, we are not restricted to an unnamed function, and I can refer to the function by the name or by the variable.

for more info you must look into this article...

http://www.permadi.com/tutorial/jsFunc/index.html

Andere Tipps

The name of the following function is m1. It is stored in the current scope as m1. It is accessible everywhere in this scope regardless of code order.

function m1(){}

The following function has no name. It is stored in the current scope as m2. It is accessible only in lines after it.

var m2 = function(){}

You can also assign named functions to other variables:

var m1 = m2;
function m2(){}
var m3 = function m4(){};
var m5 = function(){};

In Firefox's console:

>>> m1
m2()

>>> m2
m2()

>>> m3
m4()

>>> m4
ReferenceError: m4 is not defined

>>> m5
function()

If you only wish to have a function avaliable by specific name, the minimum way is to write without assignment. Just because you don't need to perform an extra action and write extra code, you just need to have a function you can call.

A way with assignment you've written is an example of using an anonymous function, and it's not practically the case that needs an anonymous function. One example use of this feature is that you can pass actions to certain functions as arguments. Take a look at this page of jQuery docs on hide. This function accepts two arguments: the length of animation and the action to do after it's complete. You may not need that action anywhere else, so why make another identifier and clutter your namespace? There might be reasons, but these are beyond the scope of this question.

JS syntax allows both, but it's a side effect of having anonymous functions avaliable in JS.

So it's a matter of choice and habits.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top