gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:33:04 25 4
gpt4 key购买 nike

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

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

console.log(aFunction.name); // aFunction

我发现这很有趣,并决定尝试声明为 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

为什么?

最佳答案

这是一个未命名的函数。有时称为“匿名”函数或“lambda”。

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

如果你想给它命名,你可以这样做

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

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

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

bFunction; //=> function bFunction(a,b) { ... }
bFunction.name; //=> "bFunction"

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

对比匿名函数错误

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

//=> Uncaught TypeError: Cannot read property 'x' of undefined at <anonymous>:2:24

Vs 命名函数错误

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

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

请注意命名函数 stacktrace 如何提及 foo,这有助于我们识别包含错误的函数。

关于javascript - 创建为 var 的函数没有 .name 属性。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32852898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com