I am reading over this code and the article on MDN about closures:
function outer() {
var reference = 0;
return function() {
reference += 1;
return reference;
}
}
var x = outer();
x();
x()
x()
console.dir( x() );
Yet, I am baffled at how this code remembers state. For some reason the author of the code decided to name a variable reference
. Only thing that comes to mind is the, "physical address" meaning in this context.
When I see the lines of code from var x = ...
I am thinking the following:
- assign the anonymous function to the variable x. At this time of execution the
reference
variable of the outer function is 0 and so is it in the inner function - execute the inner function adding the variable
reference
to 1 then I loose track
From running the code all I can see is that the inner function creates some type of reference/pointer ,if you will, to the outer functions reference
variable which is updated each time the closure is executed. For some reason the reference
variable's value persists upon further execution almost like a static variable in php. Is this why MDN says that a closure "remembers" its environment?
Any step by step explanation would help.