Javascript "this" not set in function that was passed around

I have a class, in where I have a method that creates a function to be called by some third party library. Inside the function I want to call class members, but the "this" keyword is not set anymore at the moment the function is called. How can I get the this keyword to work inside the function?

I have an oversimplified example:

class myclass
{
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    return function(x) { this.printIt(x); };
  }
}


(new myclass).getFunc()("test");

TypeError: Cannot read properties of undefined (reading ‘printIt’)

And I also have a solution which I am not happy with, and which I expect can be done in a more elegant way:

class myclass
{
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    let self = this;
    return function(x) { self.printIt(x); };
  }
}


(new myclass).getFunc()("test");

>Solution :

class myclass {
  printIt(x) {
    console.log(x);
  }

  getFunc() {
    return function(x) {
      this.printIt(x);
    }.bind(this);
  }
}


(new myclass).getFunc()("test");

Leave a Reply