JSFiddle - React, Tailwind, and code Playground
JavaScript
const internal = (() => {
let map = new WeakMap();
return (instance) => {
if (map.has(instance)) {
return map.get(instance);
}
let o = Object.create(null);
map.set(instance, o);
return o;
}
})();
class Foo {
constructor(foo) {
internal(this).field = foo;
internal(this).method = () => {
return internal(this).field * 2;
}
}
baz() {
return internal(this).method();
}
}
let foo = new Foo(2);
console.log(foo.baz()); // 4