ECMAScript 6 function.name property

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

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

      

According to the mapping table n

should be relevant "f"

. However, the mozilla docs say it should return an empty string. Which one is correct?

+3


source to share


2 answers


Since ECMAScript 6 is currently in draft state, the answer below may become deprecated in the future.
That being said, referring to the draft specification :

Anonymous function objects that do not have a context name associated with them by this specification do not have a name property, but inherit the name % FunctionPrototype% property .

The ECMAScript 6 Wiki reads that

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



However,

Some functions are anonymous and do not have a name specified as part of their static semantics. If a function is directly assigned to an LHS where the name is statically defined, then the LHS name is used.

Note that the claims made by the wiki are not referenced (and cannot be found directly) in the draft spec, but they are reasonable assumptions.

If we make these assumptions true, the result of your function call to the function is "f"

, since the anonymous function is assigned by the LHS.
Reading the name property of an unassigned anonymous function should return an empty string.

+3


source


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

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

      



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

+1


source







All Articles