Skip to content

Instantly share code, notes, and snippets.

@Aldizh
Last active September 20, 2019 20:17
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 Aldizh/d7a689b51793bf1ca8243402f14bad98 to your computer and use it in GitHub Desktop.
Save Aldizh/d7a689b51793bf1ca8243402f14bad98 to your computer and use it in GitHub Desktop.
Basic counter that demonstrates javascript closure concept
// In the function below changeBy is a private function
// whereas increment and decrement are public and hence
// can be invoked outside the Counter's scope
function Counter(initialCounter) {
var privateCounter = initialCounter || 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
};
var counter = new Counter(1);
console.log(counter.value()); // logs 1
counter.increment();
counter.increment();
console.log(counter.value()); // logs 3
counter.decrement();
console.log(counter.value()); // logs 2
// should give an error as it is out of scope
// console.log(counter.changeBy(1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment