I'm playing with closure and have no problem understanding how inner functions have access to outer lexical environments:
function outer() {
var bar = 0;
function inner() {
console.log(bar);
}
inner();
}
outer(); // prints '0'
But what gets me is this:
function foo() {
return function inner() {
console.log(bar);
}
}
function outer() {
var bar = 0;
var fakeInner= foo(); // not the same as "var fakeInner= function () { console.log(bar); }"
fakeInner();
}
outer(); // ReferenceError: bar is not defined
Here I try to "define" an "inner function" fakeInner
by assigning it to a function expression returned from an outside function.
I used to think that JavaScript creates the fakeInner
inside with a "copy" of its code, something like: var fakeInner= function () { console.log(bar); }
, which would then have access to bar
, but this is not the case -- it appears when fakeInner
is invoked, JavaScript traces back to its definition. Am I understanding this correctly? That is, function objects (either declarations or expressions) are mere references to their definition spots, and passing them do not change their lexical environments (hence inner functions have to be defined inside with explicit syntax)?