简体   繁体   English

Javascript:var myFunc = function()与var myFunc = function myFunc()

[英]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. 在第二个示例中, arguments.callee.caller.name有效,但在第一个示例中无效。 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 . 函数是具有属性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 . 函数文字中的name是可选的,如果省略(如在第一种情况下所示),则该函数被称为匿名

This is from JavaScript: The Good Parts by Douglas Crockford : 这来自于Douglas Crockford的JavaScript:The Good Parts

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. 将函数分配给变量不会赋予函数名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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