DEV Community

Nur Nafish Ahmed Nobel
Nur Nafish Ahmed Nobel

Posted on

Emulating private methods with closures

var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}

return {
increment: function() {
changeBy(1);
},

decrement: function() {
  changeBy(-1);
},

value: function() {
  return privateCounter;
}
Enter fullscreen mode Exit fullscreen mode

};
})();

console.log(counter.value()); // 0.

counter.increment();
counter.increment();
console.log(counter.value()); // 2.

counter.decrement();
console.log(counter.value()); // 1.

Top comments (0)