I get tired of writing code like this:
class Something {
constructor() {
this.method = this.method.bind(this);
this.anotherOne = this.anotherOne.bind(this);
// ...
}
}
It's time consuming and it's easy to forget to bind a method. I aware of the class fields proposal, but it's still Stage 3 and seems to come with some issues.
My current solution (based on this answer) looks like this:
class Something {
constructor() {
// Get all defined class methods
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(this));
// Bind all methods
methods
.filter(method => (method !== 'constructor'))
.forEach((method) => { this[method] = this[method].bind(this); });
}
}
This seems to work, but I'm wondering if there is a better way, or if this method has issues that I'm not aware of.
Update: Why Do This?
The problem I have run into is that if I don't bind my class functions in the constructor, I have to remember to call them "properly" later. For example:
const classInstance = new Something();
// This fails for a non-obvious reason
someAction()
.then(classInstance.method);
// This works of course but looks like we created a useless function if you don't know better
someAction()
.then(result => classInstance.method(result));