Skip to content

Instantly share code, notes, and snippets.

@edoardocavazza
Last active October 5, 2016 20:05
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 edoardocavazza/b81a98a2d84db50e610dfe52c60be739 to your computer and use it in GitHub Desktop.
Save edoardocavazza/b81a98a2d84db50e610dfe52c60be739 to your computer and use it in GitHub Desktop.
const MAP = (typeof self.WeakMap !== 'undefined') ? new WeakMap() : false;
const PROP = '__private__';
function internal(object) {
if (MAP) {
if (!MAP.has(object)) {
MAP.set(object, {});
}
return MAP.get(object);
}
if (!this.hasOwnProperty(internal.fallbackKey)) {
this[internal.fallbackKey] = {};
}
return this[internal.fallbackKey];
}
internal.fallbackKey = PROP;
internal.destroy = function(object) {
if (MAP) {
if (MAP.has(object)) {
MAP.delete(object);
}
} else {
delete this[PROP];
}
};
@edoardocavazza
Copy link
Author

Demo

class Demo {
    constructor(id) {
        internal(this).id = id;
    }
    get fullId() {
        return `full-${internal(this).id}`
    }
}

let demo = new Demo(2);

console.log(demo.id); // undefined
console.log(demo.fillId); // "full-2"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment