Bind All Methods to a Class instance JavaScript
function bindAll(target) {
const keys = Object.getOwnPropertyNames(target.constructor.prototype);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const propOrMethod = target[key];
if (typeof propOrMethod === 'function') {
target[key] = target[key].bind(target);
}
}
}
class Test {
constructor() {
bindAll(this);
document.addEventListener('click', this.onClick);
}
onClick(e) {
console.log('click', this);
}
otherMethod(e) {
console.log('test', this);
}
}
const test = new Test();
setInterval(test.otherMethod, 1000);
This is useful when you know you need many methods of a given class to be bound to the classes instance. Another way to do this is to selectively use instance properties:
class Test {
constructor() {
document.addEventListener('click', this.onClick);
}
onClick = e => {
console.log('click', this);
}
otherMethod e => {
console.log('test', this);
}
}
Avoiding classes is another way to not have to deal with this issue 😉