Skip to content

Instantly share code, notes, and snippets.

@farooqarahim
Forked from getify/1.js
Created February 11, 2021 20:11
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 farooqarahim/efc0ccdc3ca7ed2e60b8e43740f22dc3 to your computer and use it in GitHub Desktop.
Save farooqarahim/efc0ccdc3ca7ed2e60b8e43740f22dc3 to your computer and use it in GitHub Desktop.
creating hard-bound methods on classes
class Foo {
constructor(x) { this.foo = x; }
hello() { console.log(this.foo); }
}
class Bar extends Foo {
constructor(x) { super(x); this.bar = x * 100; }
world() { console.log(this.bar); }
}
bindMethods(Foo.prototype);
bindMethods(Bar.prototype);
var x = new Foo(3);
x.hello(); // 3
setTimeout(x.hello,50); // 3
var y = new Bar(4);
y.hello(); // 4
y.world(); // 400
setTimeout(y.hello,50); // 4
setTimeout(y.world,50); // 400
var method = (function defineMethod(){
var instances = new WeakMap();
return function method(obj,methodName,fn) {
Object.defineProperty(obj,methodName,{
get() {
if (!instances.has(this)) {
instances.set(this,{});
}
var methods = instances.get(this);
if (!(methodName in methods)) {
methods[methodName] = fn.bind(this);
}
return methods[methodName];
}
});
}
})();
function bindMethods(obj) {
for (let ownProp of Object.getOwnPropertyNames(obj)) {
if (typeof obj[ownProp] == "function") {
method(obj,ownProp,obj[ownProp]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment