)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Bind All Methods to a Class instance JavaScript

  1. function bindAll(target) {
  2.   const keys = Object.getOwnPropertyNames(target.constructor.prototype);
  3.   for (let i = 0; i < keys.length; i++) {
  4.     const key = keys[i];
  5.     const propOrMethod = target[key];
  6.     if (typeof propOrMethod === 'function') {
  7.       target[key] = target[key].bind(target);
  8.     }
  9.   }
  10. }
  11.  
  12. class Test {
  13.   constructor() {
  14.     bindAll(this);
  15.     document.addEventListener('click', this.onClick);
  16.   }
  17.   onClick(e) {
  18.     console.log('click', this);
  19.   }
  20.   otherMethod(e) {
  21.     console.log('test', this);
  22.   }
  23. }
  24.  
  25. const test = new Test();
  26.  
  27. 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:

  1. class Test {
  2.   constructor() {
  3.     document.addEventListener('click', this.onClick);
  4.   }
  5.   onClick = e => {
  6.     console.log('click', this);
  7.   }
  8.   otherMethod e => {
  9.     console.log('test', this);
  10.   }
  11. }

Avoiding classes is another way to not have to deal with this issue 😉

// humor // javascript // oop
snippet.zone ~ 2021-24 /// {s/z}