Created
February 23, 2017 16:06
-
-
Save rebolyte/e9a080666ae47a4dd49ec7c0b37141a8 to your computer and use it in GitHub Desktop.
keep properties private in a closure with a getter/setter proxy
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
'use strict'; | |
// keeping things private | |
let store = (() => { | |
let debug = true; | |
let state = { | |
isLoggedIn: false, | |
user: {} | |
}; | |
// Map each of the properties from the state object to getters | |
// and setters that we'll return. | |
let proxy = Object.keys(state).reduce((hash, key) => { | |
return Object.defineProperty(hash, key, { | |
get() { | |
return state[key]; | |
}, | |
set(newVal) { | |
debug && console.log(`state changed triggered: setting ${key} to ${newVal}`); | |
state[key] = newVal; | |
}, | |
enumerable: true | |
}); | |
}, {}); | |
return proxy; | |
})(); | |
console.log(store.isLoggedIn); | |
store.isLoggedIn = true; | |
console.log(store.isLoggedIn); | |
// delete store.isLoggedIn; // <-- throws |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment