Last active
October 10, 2022 17:53
-
-
Save remyoudemans/c66cc14d5d5271c4a6e5cf0f35b76b67 to your computer and use it in GitHub Desktop.
Closures for private state
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
const makeCounter = () => { | |
let count = 0; | |
return { | |
get() { | |
return count; | |
}, | |
increment() { | |
count += 1; | |
}, | |
decrement() { | |
count -= 1; | |
} | |
} | |
} | |
const counter1 = makeCounter(); | |
counter1.get(); // 0 | |
counter1.increment(); | |
counter1.get(); // 1 | |
const counter2 = makeCounter(); | |
counter2.get(); // 0 | |
counter2.decrement(); // -1 | |
// note that counter1 hasn't changed. They have separate values |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment