I can't figure out why an unexecuted closure can capture the outer variables.
I do read about some articles about execute context
, lexical environment
, memory management
, but none of these can solve my question:
function foo() {
var a = 1;
return function() {
console.log(a);
}
}
var f = foo() // line 7
// HERE variable a was been captured
f = undefined // line 10
// HEAE variable a was been released
When the engine execute to line7, the foo execution context
was created above global execution context
, but after line7 the closure was never been execute, so the closure execution context was never been created, so was the lexical environment. foo execution context
was been popped up, the variable a
will be released.
I can't find what's wrong with my point. So why and when the variable in closure be captured?