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

Pass a class method (that uses 'this') to another class

Here is a simple snippet:

class A {
  constructor(func) {
    func();
  }
}

class B {
  constructor() {
    this.field = "hello";
    new A(this.printField);
  }

  printField() {
    console.log(this.field);
  }
}

new B();

I would expect "hello" to be printed. However, I get the following error:

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

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

It seems that after passing printField, this is now referring to A instead of B. How can I fix it?

Edit:
Yes, yes, I know. When copying the snippet I accidentally wrote new A(printField) instead of new A(this.printField). The question and the error I get are now fixed.

>Solution :

You need to capture the context somehow. For example, using an arrow function () => this.printField()

class A {
  constructor(func) {
    func();
  }
}

class B {
  constructor() {
    this.field = "hello";
    new A(() => this.printField());
  }

  printField() {
    console.log(this.field);
  }
}

new B();
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