Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final piece of javascript closures I stil don't understand

Tags:

javascript

Lets say we have defined this function in the global scope:

function createCounter() {
  var counter = 0;

  function increment() {
    counter = counter + 1;

    console.log("Number of events: " + counter);
  }

  return increment;
}

In most examples explaining closures I see executing:

createCounter();

from the global scope would just return the inner function:

function increment() {
    counter = counter + 1;

    console.log("Number of events: " + counter);
}

Now that makes total sense, because of this line in createCounter function declaration

return increment;

So my question is, why does this:

var counter1 = createCounter();

counter1();

Number of events: 1 //result

Finally get the function to work?

Essentially aren't counter1 and createCounter both pointers to that inner function which exist in the global scope?

Maybe a better way to ask this is why does counter1() work and not just return the inner function like createCounter does?

like image 745
Antonio Pavicevac-Ortiz Avatar asked Nov 20 '15 22:11

Antonio Pavicevac-Ortiz


1 Answers

No, createCounter is a function that returns a separate instance of the increment function holding a new closure with a different local counter variable.

So yes, you need the extra call to get the separate instance of the function and call that as many times as you wish. Notice that calling createCounter doesn't increase the counter, but calling counter1 or counter2 did increase it.

var counter1 = createCounter(); //local counter is still 0
var counter2 = createCounter();
counter1(); // 1
counter2(); // 1
counter1(); // 2
counter2(); // 2
like image 145
Juan Mendes Avatar answered Nov 15 '22 08:11

Juan Mendes