Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Apache License: https://www.apache.org/licenses/LICENSE-2.0
;(function (exports){
// classPrivateMethods -> WeakMap (instance -> members)
let privateMemberMap = new WeakMap();
function createInternalFunction(classPrivateMethods) {
if (!privateMemberMap.has(classPrivateMethods)) {
privateMemberMap.set(classPrivateMethods, new WeakMap());
}
function generatePrivateMemberObject(instance) {
let obj = {};
Object.entries(classPrivateMethods)
.forEach(([name, func]) => {
obj[name] = func.bind(instance);
});
return obj;
}
return function(instance) {
if (!privateMemberMap.get(classPrivateMethods).has(instance)) {
privateMemberMap.get(classPrivateMethods).set(
instance,
generatePrivateMemberObject(instance)
);
}
return privateMemberMap.get(classPrivateMethods).get(instance);
}
}
exports.createInternalFunction = createInternalFunction;
})(window);
;(function (exports){
const privateMethods = Object.seal({
_privMethod1() {
console.log(this.constructor.name, "At private method 1 on obj", _(this)._privProperty);
},
_privMethod2() {
console.log(this.constructor.name, "At private method 2 on obj", _(this)._privProperty);
_(this)._privMethod1();
},
_privMethod3() {
console.log(this.constructor.name, "At private method 3 on obj", _(this)._privProperty);
this.pubMethod4();
},
});
let _ = createInternalFunction(privateMethods);
class Class1 {
constructor(property) {
_(this)._privProperty = property;
}
pubMethod1() {
console.log(this.constructor.name, "At public method 1 on obj", _(this)._privProperty);
_(this)._privMethod1();
}
pubMethod2() {
console.log(this.constructor.name, "At public method 2 on obj", _(this)._privProperty);
_(this)._privMethod2();
}
pubMethod3() {
console.log(this.constructor.name, "At public method 3 on obj", _(this)._privProperty);
_(this)._privMethod3();
}
pubMethod4() {
console.log(this.constructor.name, "At public method 4 on obj", _(this)._privProperty);
}
}
exports.Class1 = Class1;
})(window);
let obj1 = new Class1('some');
obj1.pubMethod1();
obj1.pubMethod2();
obj1.pubMethod3();
obj1.pubMethod4();
let obj11 = new Class1('another');
obj11.pubMethod1();
obj11.pubMethod2();
obj11.pubMethod3();
obj11.pubMethod4();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment