Created
April 2, 2015 22:49
-
-
Save gamefreak/bc2263cb0399a4c07c53 to your computer and use it in GitHub Desktop.
Class method binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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