1

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?

Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • 1
    Maybe `bind`: `a.myMethod.bind(a)`? – General Grievance Nov 09 '22 at 13:34
  • Actually, I think the better solution here is to pass the `A` instance to the constructor and let the constructor invoke the instance's `myMethod`. – General Grievance Nov 09 '22 at 13:46
  • @GeneralGrievance Why? Could you elaborate in an answer? – Michael Haddad Nov 09 '22 at 13:47
  • 1
    As presented there’s no *reason* to pass just the bound method. The canonical answer provides the two most common solutions (bind, arrow function) but it’s not clear why they’re not working for you. – Dave Newton Nov 09 '22 at 13:52
  • Yeah, kinda what Dave said. And I'm wondering if there's a deeper issue that really should be solved by refactoring rather than just giving advice like, "when in doubt, always use `bind`," as this seems to be a fairly general question with a lot of possible solutions. I don't want to steer you down the wrong path. – General Grievance Nov 09 '22 at 13:59

2 Answers2

1

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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Ibrahimtp
  • 69
  • 3
0

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