Where Is The Immutable Binding Record Of The Identifier In A Named Function Expression Stored In Javascript?
Solution 1:
Where is the immutable binding record of the function name stored?
In an extra lexical environment record that you cannot see :-)
How come the function name
foooutweighvar foo = 1when resolved inside NFE?
In fact it doesn't. You can declare a new local var foo in the function scope without any collisions, but if you don't then the free foo variable does resolve to the immutable binding. It does outweigh global foo variables higher in the scope chain, however.
var foo = 1;
(functionfoo() { "use strict";
var foo = 2;
console.log(foo); // 2
}());
(functionfoo() { "use strict";
console.log(foo); // function …
foo = 2; // Error: Invalid assignment in strict mode
}());
Are their binding records stored in the same lexical environment?
No. Every named function expression is enclosed in an extra lexical environment that has a single, immutable binding for the function's name initialised with the function.
This is described in the Function Definition (§13) section of the spec. While the steps for function declarations and anonymous function expressions basically are "create a new function object with that function body using the current execution context's lexical environment for the Scope", named function expressions are more complicated:
- Let
funcEnvbe the result of callingNewDeclarativeEnvironmentpassing the running execution context’s Lexical Environment as the argument - Let
envRecbefuncEnv’s environment record. - Call the
CreateImmutableBinding(N)concrete method ofenvRecpassing theIdentifierof the function as the argument. - Let
closurebe the result of creating a new Function object […]. Pass infuncEnvas the Scope. - Call the
InitializeImmutableBinding(N,V)concrete method ofenvRecpassing theIdentifierof the function andclosureas the arguments. - Return
closure.
It does construct an extra wrapper environment just for the function expression. In ES6 code with block scopes:
var x = functionfoo(){};
// is equivalent tovar x;
{
const foo = function() {};
x = foo;
}
// foo is not in scope hereWhat's behind the phenomenon that function name
foois accessible inside but invisible outside?
The foo immutable binding is not created in the current execution context's lexical environment, but in the wrapper environment which is only used for the closure around the function expression.
Post a Comment for "Where Is The Immutable Binding Record Of The Identifier In A Named Function Expression Stored In Javascript?"