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
foo
outweighvar foo = 1
when 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
funcEnv
be the result of callingNewDeclarativeEnvironment
passing the running execution context’s Lexical Environment as the argument - Let
envRec
befuncEnv
’s environment record. - Call the
CreateImmutableBinding(N)
concrete method ofenvRec
passing theIdentifier
of the function as the argument. - Let
closure
be the result of creating a new Function object […]. Pass infuncEnv
as the Scope. - Call the
InitializeImmutableBinding(N,V)
concrete method ofenvRec
passing theIdentifier
of the function andclosure
as 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 here
What's behind the phenomenon that function name
foo
is 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?"