Skip to content

Instantly share code, notes, and snippets.

@oakfang
Created March 2, 2017 08:14
Show Gist options
  • Save oakfang/e65e15568119f8bed9ee11f3fb4e0766 to your computer and use it in GitHub Desktop.
Save oakfang/e65e15568119f8bed9ee11f3fb4e0766 to your computer and use it in GitHub Desktop.
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