简体   繁体   中英

Javascript: var myFunc = function() vs. var myFunc = function myFunc()

What is the difference between these?

var myFunc = function() {
  // ...
};

vs.

var myFunc = function myFunc() {
  // ...
};

In the 2nd example, arguments.callee.caller.name works, but not in the first one. Is there anything wrong with the 2nd syntax?

The second one has a name while the first one doesn't. Functions are objects that have a property name . If the function is anonymous then it has no name.

var a = function(){}; // anonymous function expression
a.name; //= empty

var a = function foo(){}; // named function expression
a.name; //= foo

The name in a function literal is optional, if omitted as in the first case you show the function is said to be anonymous .

This is from JavaScript: The Good Parts by Douglas Crockford :

A function literal has four parts. The first part is the reserved word function . The optional second part is the function's name. The function can use its name to call itself recursively. The name can also be used by debuggers and development tools to identify the function. If a function is not given a name, as shown in the previous example, it is said to be anonymous .

The first function doesn't have a name.

Assigning a function to a variable doesn't give the function a name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM