javascript - ECMAScript 6 的 function.name 属性

标签 javascript ecmascript-6 ecmascript-harmony

快速提问:这段代码的正确结果是什么:

let f = function(){};
let n = f.name; //"" or "f"?

根据compat table , n 应具有值 "f"。然而,the mozilla docs说它应该返回一个空字符串。哪一个是正确的?

最佳答案

由于 ECMAScript 6 目前处于草案状态,下面的答案可能会在未来的某个时候过时。
也就是说,引用 the spec draft :

Anonymous functions objects that do not have a contextual name associated with them by this specification do not have a name own property but inherit the name property of %FunctionPrototype%.

ECMAScript 6 Wiki读到

If no name can be statically determined, such as in the case of an unassigned anonymous function, then the empty string is used.

但是,

Some functions are anonymous and have no name given as part of their static semantics. If the function is directly assigned to a LHS where a name is statically determinable then the LHS name is used.

请注意,规范草案中未引用(也无法直接找到)wiki 提出的声明,但它们是合理的假设。

如果我们认为这些假设为真,那么您的示例函数调用的结果将为 "f",因为匿名函数已分配给 LHS。
读取未分配的匿名函数的名称属性应该返回一个空字符串。

关于javascript - ECMAScript 6 的 function.name 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27470212/

相关文章:

javascript - 和谐解构ReferenceError : Invalid left-hand side in assignment

javascript - 如何使用 jplayer 获取进度事件

JavaScript:数字等级到字母等级

javascript - 从下拉菜单输出差异时获取空值? (Javascript)

javascript - 使用 webpack 发出源映射后无法在 chrome 中看到源代码

javascript - 如何将 ReactJS es6 代码导入 Express 应用程序?

javascript - ES5 Object.assign 等效项

javascript - 根据 Controller 中的条件语句更改 ng-class

javascript - react : Error on props update from parent (Failed to execute removeChild)

javascript - *something* if *expression* JavaScript 中的语法 (FF)