-2

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

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.

Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • The reference error is from using plain `printField` instead of `this.printField`. – Pointy Nov 01 '22 at 13:26
  • "*ReferenceError: printField is not defined*" means *exactly* what it says: you have no variable defined called `printField`. This is not due to how `this` is handled, although that's *also* a problem in your code. See [How to access the correct `this` inside a callback](https://stackoverflow.com/q/20279484) – VLAZ Nov 01 '22 at 13:27
  • @VLAZ 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. – Michael Haddad Nov 01 '22 at 13:31

2 Answers2

1
Uncaught ReferenceError: printField is not defined

It seems that after passing printField

You aren't passing printField. The error says that you don't have a variable named printField.

To access the property of an object you need to first access the object.

new A(this.printField);

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

After you fix the error the message is complaining about, you will get a problem like that. (but this will point to window or be undefined depending on your environment).

That is covered by this duplicate: How to access the correct this inside a callback.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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();
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98