Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Created February 23, 2017 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebolyte/e9a080666ae47a4dd49ec7c0b37141a8 to your computer and use it in GitHub Desktop.
Save rebolyte/e9a080666ae47a4dd49ec7c0b37141a8 to your computer and use it in GitHub Desktop.
keep properties private in a closure with a getter/setter proxy
'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