Last active
May 7, 2020 10:01
-
-
Save lorenzofelletti/b85dee20afc4da3e5ddbc4db00809ad3 to your computer and use it in GitHub Desktop.
JS Closures
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
function makeCounter(i) { | |
let count = i; | |
let toString = () => `The count is ${count}.`; | |
return { | |
add: () => ++count, | |
sub: () => --count, | |
val: () => 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