Created
March 2, 2017 08:14
-
-
Save oakfang/e65e15568119f8bed9ee11f3fb4e0766 to your computer and use it in GitHub Desktop.
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 getPrivateContainer = () => { | |
const privateProperties = new WeakMap(); | |
const getPrivate = (instance, prop) => { | |
if (!privateProperties.has(instance)) { | |
privateProperties.set(instance, {}); | |
} | |
return privateProperties.get(instance)[prop]; | |
}; | |
const setPrivate = (instance, prop, value) => { | |
if (!privateProperties.has(instance)) { | |
privateProperties.set(instance, {}); | |
} | |
privateProperties.get(instance)[prop] = value; | |
}; | |
return { getPrivate, setPrivate }; | |
}; | |
const getPrivateClass = clsFactory => clsFactory(getPrivateContainer()); | |
const MyObject = getPrivateClass(({ getPrivate, setPrivate }) => { | |
return class { | |
constructor(x) { | |
setPrivate(this, 'x', x); | |
} | |
getX() { | |
return getPrivate(this, 'x'); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment