Home > OS >  "this" is undefined inside a class method, when it is used as a callback
"this" is undefined inside a class method, when it is used as a callback

Time:11-09

I know there are many questions about this, and I have read many answers and references, including this canonical answer. However, I am not able to derive a solution to my specific problem.

Here is a sample code:

class A {
  myField;

  constructor(myField) {
    this.myField = myField;
  }

  myMethod() {
    console.log(this.myField);
  }
}

class B {
  constructor(myFunc) {
    myFunc();
  }
}

const a = new A("Hello");
const b = new B(a.myMethod);

I get this error:

Cannot read properties of undefined (reading 'myField')

It seems that this inside myMethod is undefined and does not refer to the instance of A, as I would expect (coming from C#...).

What can I do to refer to myField?

CodePudding user response:

the problem is that this is being called in another class (in this case class B) which is not "connected" with class A. You could resolve this by passing the instance "this" in the myMethod function:

class A {

  constructor(myField) {
    this.myField = myField;
  }

  myMethod(instance) {
    console.log(instance.myField);
  }
}

class B {
  constructor(myFunc, instance) {
    myFunc(instance);
  }
}

const a = new A("Hello");
const b = new B(a.myMethod, a);

CodePudding user response:

to refer to your field, you have to use the bind method. bind() is used to borrow methods from another object. In your case the only thing you need to do is bind. Read briefly about it here https://www.w3schools.com/js/js_function_bind.asp

  • Related