-1

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");
Zak
  • 6,976
  • 2
  • 26
  • 48
Veda
  • 2,025
  • 1
  • 18
  • 34

1 Answers1

2

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

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


(new myclass).getFunc()("test");
Konrad
  • 21,590
  • 4
  • 28
  • 64