快速提问:这段代码的正确结果是什么:
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%.
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/