Why would you assign a function to a variable instead of declaring a named function?

Why should I do this:

var myfunc = function() { /* code */ }; ... myfunc(); 

instead of this:

 function myfunc() { /* code */ } ... myfunc(); 

Are there any advantages to using one over the other? I saw both examples used in different places.

+4
source share
3 answers

The only difference, as far as I can tell, is that an anonymous function cannot call itself recursively while a named function can. There is a third type of construct that combines both of them, that is, you can have a named function expression:

 var myfunc = function myfunc() { /* code */ }; 
+4
source

If the function is declared normally, the function name (its identifier) ​​will not be deleted, even if the identifier is updated. The identifier will only be deleted after completion of its scope.

 function myfunc() { /* code */ }; if (delete myfunc) { //will fail alert('myfunc deleted'); } else { alert('can not delete myfunc'); } myfunc = null; if (delete myfunc) { //will still fail alert('myfunc deleted'); } else { alert('can not delete myfunc'); } var myfunc = null; if (delete myfunc) { //will still fail alert('myfunc deleted'); } else { alert('can not delete myfunc'); } 

But if a function declaration is assigned to a variable, its identifier can be deleted. This is especially useful when you need to create a global function, but use it only temporarily so that it can be deleted when it is no longer needed, or to avoid a possible conflit identifier with third-party scripts.

 var myfunc = function() { /* code */ }; if (delete myfunc) { //will succeed alert('myfunc deleted'); } else { alert('can not delete myfunc'); } //or... var myfunc = function myrealfunc() { /* code */ }; if (delete myfunc) { //will succeed alert('myfunc deleted'); } else { alert('can not delete myfunc'); } 
+3
source

There are several differences, mostly pragmatic. When you have a "var" function, a normal assumption is a kind of "locally" scoped function (I think a nested function). When you do this, function myFunction() {} , the function is basically considered a global scope (although you can wrap it inside an anonymous function as well).

In the case of the javascript class, if you want to create a locally restricted function, you will need to use "var" to declare it.

 var myClass = function() { var test = function() { //This function has local scope } }; 

Adding to the comments above is a simple example.

  var myVariable = resultFunction(); function resultFunction() { return 1; } 

The above code will work. But you can not do the following

  var myVariable = resultFunction(); var resultFunction = function() { return 1; }; 

But you can do

  var resultFunction = function() { return 1; }; var myVariable = resultFunction(); 
-2
source

All Articles