Understanding Closures in Javascript
This example shows how you create a closure which uses an alert function that can be incremented and reused/passed around.
- In the console call funcStorer() and you will see the counter increment.
- Then call funcStorer2() and you will see a seperate counter increment.
- The variable x is private to the closureAlert function.
- When funcStorer is called closureAlert runs, it returns alerter.
- When functStorer is called again it doesn't call closureAlert again it calls what it returns alerter.
var closureAlert = function() {
var x = 0;
var alerter = function() {
alert(++x);
}
return alerter;
}
var funcStorer = closureAlert(); // reference to alerter();
var funcStorer2 = closureAlert(); // second seperate reference to alerter();