问题
This is a named function expression with the name test
. Inside, I assign 123
to a variable, also named test
. Then test
is logged. The function prints its body in the console, but not 123
. What is the reason for such behavior?
(function test() {
test = 123;
console.log( test );
}());
Where does my explanation of function execution fail?
- Start of function execution:
test
is a local variable that references the function itself - Local variable
test
is reassigned to number123
console.log(test)
shows the number123
.
回答1:
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:
- Let funcEnv be the result of calling NewDeclarativeEnvironment passing the running execution context’s Lexical Environment as the argument
- Let envRec be funcEnv’s environment record.
- Call the CreateImmutableBinding concrete method of envRec passing the String value of Identifier as the argument.
- 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.
- Call the InitializeImmutableBinding concrete method of envRec passing the String value of Identifier and closure as the arguments.
- 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.
来源:https://stackoverflow.com/questions/24021489/why-can-t-i-assign-values-to-a-variable-inside-a-named-function-expression-with