When we have an inner function that access a variable x1
defined in the lexical environment of its outer function, how the JavaScript engines handle keeping the x1
in the memory ?
Do they keep the already created execution context with its lexical environment of the outer function or they create a new lexical environment and copy the variable binding into it then link it as the outer
lexical environment for the lexical environment of the inner function and destroy the execution context with the lexical environment of the outer function.
Can we consider a closure
as a Lexical Environment
?
- The outer function is
func1
. - The inner function is
func2
. - The outer variable is
x1
defined insidefunc1
.
In the following code:
function func1() {
var x1 = 1;
return function func2() {
var x2 = 2;
return [x1, x2];
}
}
func1()();