function's closure code example
Example 1: javascript closure
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2));
console.log(add10(2));
Example 2: 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; }
};
})();
counter.increment(); counter.increment();
counter.decrement();
counter.value();