Why can’t I assign values to a variable inside a named function expression with the same name?

为君一笑 提交于 2019-11-27 22:27:27

I believe this piece of the ecma spec explains this behavior. This relates specifically to named Function Expressions

The production

FunctionExpression : function Identifier ( FormalParameterListopt ) { FunctionBody }

is evaluated as follows:

  1. Let funcEnv be the result of calling NewDeclarativeEnvironment passing the running execution context’s Lexical Environment as the argument
  2. Let envRec be funcEnv’s environment record.
  3. Call the CreateImmutableBinding concrete method of envRec passing the String value of Identifier as the argument.
  4. Let closure be the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in funcEnv as the Scope. Pass in true as the Strict flag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.
  5. Call the InitializeImmutableBinding concrete method of envRec passing the String value of Identifier and closure as the arguments.
  6. Return closure.

The use of CreateImmutableBinding when creating the scope of a named Function Expression, creates the identifier (in this case test) as an immutable variable. That is why assignment to it does not change its value.

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