In this example
var a = 1;
( function(x) {
function inner() {
alert(a);
alert(x);
alert(y);
}
var y = 3;
inner();
})(2);
When does function inner
get created? during execution time or parsing time of outer anonymous function?
What is in the scope chain of function inner
?
What is the difference between the execution context and scope chain of function inner
?
Thanks for enlighting me in advance!
One is created each time the outer function is executed.
When you execute it, that execution gets a variable object (technically the spec calls this the "binding object of the variable environment"); that's backed by the variable object created for the outer function call that created
inner
; that's backed by the global variable object. So:Every function call gets its own execution context. I'm not quite sure I understand what's being asked here.
You can read up on all of this stuff (if you're willing to wade through the treacle of turgid prose) in Section 10 of the spec, and in particular section 10.4.3: "Entering Function Code".
The
inner
function gets created just before the anonymous function is executed, by the Variable Instantiation process.The
[[Scope]]
ofinner
when it's executed contains:inner
(it's empty because there are no variable/function declarations inside it)x
,y
andinner
.a
and other properties...Edit: To clarify your second question:
Are two different concepts, an execution context is created just before a piece of code (which can be either global code, function code or eval code) is executed.
I think this might be easier to explain with your code:
In the Step 1, the anonymous function is created, the current scope (only containing the global object) is stored in this moment on the function
[[Scope]]
property.In the Step 2, this anonymous function is executed, a new execution context is created (a function code execution context), at this moment a new lexical environment is created (the Variable Object of this function is created), all function argument identifiers (in this case only
x
), identifiers of function declarations (inner
) and identifiers of variable declarations (y
) are bound as non-deletable properties of this new variable object (which is the new lexical scope).In the Step 3 the
inner
function is executed, this creates a new execution context, another Variable Object is injected into the scope chain, but in this case since nothing is declared insideinner
and it doesn't have any formal parameters, it will be just an empty object.See also this answer, the first part I talk about the
with
statement but in the second part it's about functions.