var x = 5;
function f0() {
return function () {
var y = 10;
var z = x + y;
console.log('x + y is: ' + z);
}
}
var myFunc = f0();
myFunc();
x = 10;
myFunc();
In the example above, I expected x + y is: 15
to be printed in the second time as well. Because, to the best of my knowledge, what is returned from f0
is a closure. I thought that a closure takes a snapshot of the variables at its environment at the time it is defined. Hence, I thought that changing x
with x = 10;
wouldn't affect the free variables used in a closure.
But apparently I was wrong. Could you tell me why does changing x
change the result of the function which is returned from f0
?
- Is it because what is returned from
f0
is not a closure? - Is it because a closure does not record the values of the variables at the scope it is being returned to?
- Is it because of another reason?