The inner
function gets created just before the anonymous function is executed, by the Variable Instantiation process.
The [[Scope]]
of inner
when it's executed contains:
- The empty Variable Object of
inner
(it's empty because there are no variable/function declarations inside it)
- The Variable Object of the anonymous function, which contains
x
, y
and inner
.
- The Global Object, that will contain
a
and other properties...
Global (3) Anonymous VO (2) inner VO (1)
________ ________ ________
| a = 1 | <--------- | x = 2 | < -------- | |
| ... | | y = 3 | ¯¯¯¯¯¯¯¯
¯¯¯¯¯¯¯¯ | inner |
¯¯¯¯¯¯¯¯
Edit: To clarify your second question:
What is the difference between the execution context and scope chain of function inner?
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:
var a = 1;
(function(x) { // Step 1
function inner() {
alert(a);
alert(x);
alert(y);
}
var y = 3;
inner(); // Step 3
})(2); // Step 2
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 inside inner
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.