closure
var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value()); // logs 0
counter.increment();
counter.increment();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1
var counter = (function() { //exposed function references private state (the outer function’s scope / lexical environment) after outer returns.
var privateCounter = 0;
function changeBy(val) { privateCounter += val; }
return { increment: function() {changeBy(1); },
decrement: function() {changeBy(-1);},
value: function() {return privateCounter; }
};
})();
counter.increment(); counter.increment();
counter.decrement();
counter.value(); // 1