What's the reasoning behind the 'name' property of a named JavaScript function expression returning the assigned function's variable name?

时间:2019-04-16 22:41:36

标签: javascript function

I'm curious why a named function expression's name property is the value of the function declaration construct's name, rather than the variable that can be used to execute the function.

function functionDeclaration(){
   return;
}

var anonymousFunctionExpression = function(){
   return;
}

var namedFunctionExpression = function functionName(){
  return;
}


console.log(functionDeclaration.name);//As expected, function name is 'functionDeclaration'
console.log(anonymousFunctionExpression.name);//As expected, function name is 'anonymousFunctionExpression'
console.log(namedFunctionExpression.name);//Why is the function's name 'functionName' and not 'namedFunctionExpression?' 

1 个答案:

答案 0 :(得分:-2)

That's just how it works. If the function in the function expression is named, that name (on the right of the =) will be used - otherwise, if not named, the .name will give you the variable name the function was assigned to when the function was created. (If it's a function declaration and not a function expression, then the .name is just the name of the declared function.)

Note that if you reassign a function created anonymously, its name remains the original variable name the function was assigned to. This is what's happening in case 2, when the interpreter must infer the variable name:

const fn = () => {};
const fn2 = fn;
console.log(fn.name);
console.log(fn2.name);

In cases 1 and 3, the interpreter does not need to infer the variable name, because the function has an explicit name already when it was defined:

function functionDeclaration(){
    //   ^^^^^^^^^^^^^^^^^^^
   return;
}
// and
var namedFunctionExpression = function functionName(){
    return;                            ^^^^^^^^^^^^
}

The interpreter would only keep track of the namedFunctionExpression if it needs to infer the function name from its creation context (which is an ES2015 feature) - and this inference is only done in case 2.