Skip to content

Instantly share code, notes, and snippets.

@gamefreak
Created April 2, 2015 22:49
Show Gist options
  • Save gamefreak/bc2263cb0399a4c07c53 to your computer and use it in GitHub Desktop.
Save gamefreak/bc2263cb0399a4c07c53 to your computer and use it in GitHub Desktop.
Class method binding
function bound(object, key, descriptor) {
let boundMethodId = Symbol('bound-method-'+key);
let theMethod = descriptor.value;
delete descriptor.value;
delete descriptor.writable;
descriptor.get = function() {
//Memoize it per instance so we can remove listeners
return this[boundMethodId] || (this[boundMethodId] = theMethod.bind(this));
};
return descriptor;
}
class Greeter {
constructor(name) {
this.name = name;
}
@bound greet1() {
console.log('Hello, ' + this + '!');
}
greet2() {
console.log("Hello, " + this + '!');
}
toString() {
return this.name;
}
}
var greeter = new Greeter('World');
setTimeout(greeter.greet1, 1);
setTimeout(greeter.greet2, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment