-2

See the example below. Inside of a callback A.handleEvent, I was expecting "this" to be an instance of A instead of B, even though it is being called from B.

class A {
  constructor() {
    this.text = 'A';
    this.b = new B(this);
  }

  handleEvent = () => {
    console.log(this.text); // outputs 'B' instead of 'A'
  }
}

class B {
  constructor(a) {
    this.text = 'B';
    this.a = a;
    setTimeout(() => {
      this.handleEvent();
    }, 1000);
  }

  handleEvent = () => {
    this.a.handleEvent();
  }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

1 Answers1

-2

The example that you gave didn't work but what you probably want to do is bind the this of the function to the this of the class:

class A {
  constructor() {
    this.text = 'A';
    this.b = new B(this);

    // bind the this of handleEvent permanently to the this of the class.
    this.handleEvent = this.handleEvent.bind(this);
  }

  handleEvent = () => {
    console.log(this.text); // outputs 'A'
  }
}

class B {
  constructor(a) {
    this.text = 'B';
    this.a = a;
    setTimeout(() => {
      this.handleEvent();
    }, 1000);
  }

  handleEvent = () => {
    this.a.handleEvent();
  }
}

BTW, here is a great youtube tutorial on bind

nloomans
  • 220
  • 2
  • 11