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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With