DEV Community

Discussion on: A super-easy way to determine 'this' in JavaScript

Collapse
 
efpage profile image
Eckehard • Edited

Hy all,
sometimes the JS-implementation of this is real strange. In callback functions, this is bound to the caller, not the object that defined the function. I found this very helpful to makes things more consistent:

// bind all methods to the constructor 
function autobind(instance) {
  let proto = Object.getPrototypeOf(instance);
  let propertyNames = Object.getOwnPropertyNames(proto);
  for (let name of propertyNames) {
    let value = proto[name];
    if ((typeof value === 'function')) {
      if (name !== 'constructor')
        instance[name] = proto[name].bind(instance);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This is used in the constructor:

class test{
    constructor() {
        autobind(this)  // bind all methods to the constructor
        ....
Enter fullscreen mode Exit fullscreen mode

This function is part of my DML-framework too...