创建为var的函数没有.name属性.为什么?

Igo*_*kiy 2 javascript function object

今天在关于JS的演讲中,我们(学生)被告知在JavaScript中,一切都是对象.例如,提供了以下代码:

// functions are objects
function aFunction(a, b) {
    // do something
};

console.log(aFunction.name); // aFunction
Run Code Online (Sandbox Code Playgroud)

我发现这很有趣,并决定尝试声明的函数var funcName = function(...将以相同的方式行事.它没有:

function aFunction(a, b) {
    return a + b;
}

var bFunction = function(a, b) {
    return a + b;
};

console.log(aFunction.name); // aFunction
console.log(bFunction.name); // empty string
Run Code Online (Sandbox Code Playgroud)

为什么?

Tha*_*you 7

这是一个未命名的功能.有时称为"匿名"功能或"lambda".

function(a, b) {
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要它命名,你可以做到

var bFunction = function bFunction(a, b) {
    return a + b;
};
Run Code Online (Sandbox Code Playgroud)

但这有点多余,如果你希望命名你的函数,最好把它写成命名函数

function bFunction(a, b) {
    return a + b;
};

bFunction;       //=> function bFunction(a,b) { ... }
bFunction.name;  //=> "bFunction"
Run Code Online (Sandbox Code Playgroud)

至于下面的评论,使用命名函数的不那么明显的好处是它们堆栈跟踪更好.也就是说,如果您经常在代码中使用匿名函数,并且其中一个函数发生错误,则堆栈跟踪将不会提供太多信息.

比较匿名函数错误

(function() { undefined.x; })()

//=> Uncaught TypeError: Cannot read property 'x' of undefined at <anonymous>:2:24
Run Code Online (Sandbox Code Playgroud)

与命名的函数错误

(function foo() { undefined.x; })()

//=> Uncaught TypeError: Cannot read property 'x' of undefined at foo (<anonymous>:2:28)
Run Code Online (Sandbox Code Playgroud)

注意命名函数stacktrace如何提及foo哪些有助于我们识别包含bug的函数.

  • 虽然如果对变量使用与函数声明相同的名称,但它是多余的.但是像`var x = function y(){}`这样的东西可能有意义. (2认同)