Created
January 6, 2019 10:30
-
-
Save adrianmcli/d4636583fb3cc64ccd4660c4191f5bd9 to your computer and use it in GitHub Desktop.
Example of encapsulating state with a function that return objects.
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 = (initVal = 0) => { | |
let count = initVal; | |
const get = () => count; | |
const set = x => (count = x); | |
const inc = () => count++; | |
const dec = () => count--; | |
return Object.freeze({ | |
get, | |
set, | |
inc, | |
dec, | |
}); | |
}; | |
// create the counter object | |
const myCounter = makeCounter(); | |
// these re-assignments do nothing because object is frozen | |
myCounter.get = null; | |
myCounter.set = null; | |
// let's test our counter out | |
console.log(myCounter.get()); // 0 | |
myCounter.set(2); | |
console.log(myCounter.get()); // 2 | |
myCounter.inc(); | |
console.log(myCounter.get()); // 3 | |
myCounter.dec(); | |
myCounter.dec(); | |
console.log(myCounter.get()); // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment