closures i js code example
Example 1: es6 closures
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1.value());
counter1.increment();
counter1.increment();
alert(counter1.value());
counter1.decrement();
alert(counter1.value());
alert(counter2.value());
Example 2: closure in javascript
A closure is a function bundeled together with its lexical scope