ECMAScript 6's function.name property

﹥>﹥吖頭↗ 提交于 2021-02-10 03:21:41

问题


Quick question: what's the correct result for this code:

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

According to the compat table, n should have the value "f". However, the mozilla docs say that it should return an empty string. Which one is correct?


回答1:


Since ECMAScript 6 is currently in draft state, the answer below may become outdated sometime in the future.
That being said, referencing 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%.

The ECMAScript 6 Wiki reads that

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

however,

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.

Note that the claims made by the wiki aren't referenced (and can't directly be found) in the spec draft, but they're reasonable assumptions.

If we take those assumptions to be true, the result of your sample function call would be "f", since the anonymous function is assigned to a LHS.
Reading the name property of an unassigned anonymous function should return an empty string.




回答2:


It will return "f", in your example, as well as in other variations:

let f = function(){}
const f = function(){}
var f = function(){}
f = function(){}  // assignment
let f = () => {}
// etc.

The relevant bits in ES6 spec draft are all the occurrences of SetFunctionName. In the case of your example, see its invocation in Section 13.2.1.4. It applies only when the RHS syntactically is an anonymous function literal.



来源:https://stackoverflow.com/questions/27470212/ecmascript-6s-function-name-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!