Skip to content

Instantly share code, notes, and snippets.

@lorenzofelletti
Last active May 7, 2020 10:50
Show Gist options
  • Save lorenzofelletti/be79f566ec6442d025685e4eb128b220 to your computer and use it in GitHub Desktop.
Save lorenzofelletti/be79f566ec6442d025685e4eb128b220 to your computer and use it in GitHub Desktop.
A version of the other gist closure.js but with a simpler syntax for beginners
function makeCounter(initialValue) {
let count = initialValue;
function toString() {
return 'The count is ' + count +'.';
}
return {
add: function() { return ++count },
sub: function() { return --count },
val: function() { return count },
toString: toString
};
}
var counter = makeCounter(0);
console.log(counter.add()) // 1
console.log(counter.val()) // 1
console.log(counter.sub()) // 0
console.log(counter.add()) // 1
console.log(counter.add()) // 2
console.log(counter.toString()) // The count is 2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment