Skip to content Skip to sidebar Skip to footer

Es6 Javascript Class Using This Inside A Callback

The new es6 class allows you to use the self reference variable this inside methods. However if a class method has a sub function or a callback, that function/callback no longer ha

Solution 1:

You have the following options:

1) Use an arrow function:

classClassName {
  // ...aMethod(){
    letaFun = () => {
      this.dir;// ACCESS to class reference of this
    }
  }
}

2) Or the bind() method:

classClassName {
  // ...aMethod(){
    var aFun = function() {
      this.dir;// ACCESS to class reference of this
    }.bind(this);
  }
}

3) Store this in a specialised variable:

classClassName {
  // ...aMethod(){
    var self = this;
    functionaFun() {
      self.dir;// ACCESS to class reference of this
    }
  }
}

This article describes the necessary details about this and arrow functions in JavaScript.

Solution 2:

Put a reference to dir in aMethod(), then use that in aFunc like

aMethod() {
    var tempDir = this.dir;
    aFunc() {
        console.log(tempDir);
    }
}

Post a Comment for "Es6 Javascript Class Using This Inside A Callback"