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.