0

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:

  1. 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
  2. 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.

Robert
  • 10,126
  • 19
  • 78
  • 130
  • If you want to see a more technical discussion of how closures work at the memory level see this answer: http://stackoverflow.com/questions/26061856/javascript-cant-access-private-properties/26063201#26063201 – slebetman Jul 03 '15 at 20:59
  • Well I looked over the wikipedia article on closures and this line made sense with my line of thinking: " A closure—unlike a plain function—allows the function to access those captured variables through the closure's reference to them, even when the function is invoked outside their scope." – Robert Jul 03 '15 at 21:15

0 Answers0