Created
August 11, 2015 13:31
-
-
Save maisnamraju/460a28b3177ab0b16edf to your computer and use it in GitHub Desktop.
Example of a closure
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
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