Skip to content

Instantly share code, notes, and snippets.

@maisnamraju
Created August 11, 2015 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maisnamraju/460a28b3177ab0b16edf to your computer and use it in GitHub Desktop.
Save maisnamraju/460a28b3177ab0b16edf to your computer and use it in GitHub Desktop.
Example of a 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment