I have a JavaScript question. Let me quote from the book ‘Learning jQuery’, page 389-390. The question concerns Closures.
I don’t understand why “the second call to outerFn() is not resetting the value of outerVar, but [is], rather, creating a new instance of outerVar, bound to the scope of the second function call.
What is it about JavaScript that would make this so? What do I need to know about JavaScript so that I could infer this for myself?
The rest of the email is the quotation from the book.
function outerFn() {
var outerVar = 0;
function innerFn() {
outerVar++;
$('#example-7').print('outerVar = ' + outerVar);
}
return innerFn;
}
var fnRef = outerFn();
fnRef();
fnRef();
var fnRef2 = outerFn();
fnRef2();
fnRef2();
Now our function calls have more interesting behavior:
outerVar = 1
outerVar = 2
outerVar = 1
outerVar = 2
We get a mix of the two earlier effects. The calls to innerFn() through each
reference increment outerVar independently. Note that the second call to
outerFn() is not resetting the value of outerVar, but rather creating a new
instance of outerVar, bound to the scope of the second function call. The
upshot of this is that after the above calls, another call to fnRef() will
print the value 3, and a subsequent call to fnRef2() will also print 3. The
two counters are completely separate.
You might be over thinking it.
As always, every time a call to
outerFnis made, it will create a newouterVarvariable for that particular invocation of the function — it’s part of it’s local scope. Thus, any functions that are within the scope of the particular call toouterFnthat are returned (or passed along somehow) will have continue to have access to that scope — a closure.