0

I am bit confused by the following JavaScript code:

    // Because this function returns another function that has access to the
    // "private" var i, the returned function is, effectively, "privileged."

    function makeCounter() {
      // `i` is only accessible inside `makeCounter`.
      var i = 0;

      return function() {
        console.log( i++ );
      };
    }

    // Note that `counter` and `counter2` each have their own scoped `i`.

    var counter = makeCounter();
    counter(); // logs: 1
    counter(); // logs: 2

    var counter2 = makeCounter();
    counter2(); // logs: 1
    counter2(); // logs: 2

    i; // ReferenceError: i is not defined (it only exists inside makeCounter)

I don't understand how come the i variable in counter and counter2 aren't referring to the same i value?

My understanding is that counter and counter2 should reference the same function since both have been assigned the same function and a function is a "reference datatype" and shouldn't create a separate copy.

Also, how is it possible the counter and counter2 access the "private" value set in makecounter function?

Andy
  • 541
  • 2
  • 4
  • 14
  • http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – akonsu Jan 08 '14 at 15:12
  • They're different instances of the same function. Each instance has its own scope, it's own `i`, etc. You should read up on this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript – matthewpavkov Jan 08 '14 at 15:13

2 Answers2

2

i is local to makeCounter.

You get a new i each time that function is invoked.

The anonymous function defined inside that function has access to i because it is defined inside makeCounter.

That function is returned, so it is available outside makeCounter but it still has access to i because of where it was defined.

My understanding is that counter and counter2 should reference the same function since both have been assigned the same function

They haven't been assigned the same function. A new function was created each time makeCounter was invoked.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I think get it. So it doesn't matter that the inside function is being used outside where it was declared and it will **always** have access to the _i_ varaible that's being initialised in the parent function? – Andy Jan 08 '14 at 15:19
0

One thing you need to understand is that Javascript uses static scoping. So the variable i is only available in the scope of makeCounter function.

When you are calling makeCounter() it initializes i to 0 and returns a new function object. And for each function object has its own instance of i.

Ivey
  • 499
  • 4
  • 13