Created
September 10, 2021 15:39
-
-
Save aidan-harding/ef3146229af1e205e847075057f5c3f1 to your computer and use it in GitHub Desktop.
Using a constructor to rebind "this" in classes, solving the problem of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#binding_this_with_prototype_and_static_methods
This file contains 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
class MyClass { | |
constructor() { | |
const self = this; | |
Object.getOwnPropertyNames( MyClass.prototype ) | |
.filter(name => name.indexOf('_') === 0) | |
.filter(name => typeof self[name] === 'function') | |
.forEach(function(name) { | |
self[name.substr(1)] = function() { | |
self[name].apply(self, arguments); | |
} | |
}); | |
} | |
name = 'Aidan'; | |
_hello() { | |
console.log(`Hello ${this.name}`); | |
} | |
} | |
let instance = new MyClass(); | |
instance.hello(); | |
instance._hello(); | |
let f = instance.hello; | |
f(); | |
let f2 = instance._hello; | |
f2(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment