Javascript: var myFunc = function() vs. var myFunc = function myFunc() - Stack Overflow

What is the difference between these?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?

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?

Share Improve this question asked Jul 1, 2013 at 3:01 vcardillovcardillo 1,7063 gold badges24 silver badges30 bronze badges 2
  • 1 var func=function F(){}; will make F() available inside function block, but not outside. – Passerby Commented Jul 1, 2013 at 3:07
  • arguments.callee is deprecated, so use named function expressions if you need that kind of functionality. – holographic-principle Commented Jul 1, 2013 at 3:42
Add a ment  | 

3 Answers 3

Reset to default 7

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744395838a4572134.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信