Example of a closure
var scoreCounter = (function() {
var score = 0;
return {
incrementBy: function(a) {
score+=a;
},
decrementBy: function(b) {
score-=b;
},
getValue: function() {
return score;
}
};
})();
console.log(scoreCounter.getValue()); // logs 0scoreCounter.incrementBy(10);
scoreCounter.incrementBy(5);
console.log(scoreCounter.getValue()); // logs 15scoreCounter.decrementBy(2);
console.log(scoreCounter
.getValue()); // logs 13
No comments:
Post a Comment