Last active
September 20, 2019 20:17
-
-
Save Aldizh/d7a689b51793bf1ca8243402f14bad98 to your computer and use it in GitHub Desktop.
Basic counter that demonstrates javascript closure concept
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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