Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading