0

I have 2 classes -> class A, class B

class A -> does some logic processing

class B -> connect to websocket endpiont and receives data.

class A {
  constructor() {}
  register() {
    this.otherClass = new B() // class B instance, connects to websocket
    this.otherClass.delegate = {
      onmessage(message) {
        //**this** key in this scope showing class B methods
        console.log(message) //I am getting message here
        this.processMessage(message) //this is not working
      }
    }

  }

  processMessage(message) {
    console.log(message) //but I am not getting message here
  }
}

How to call processMessage function from class B

Rushikesh Koli
  • 23
  • 1
  • 1
  • 6
  • Define `onmessage` as an arrow function. That way `this` will be the same `this` you called `register` with (likely an instance of `A`). – trincot May 11 '23 at 09:23
  • ```onmessage``` function is present on ```class B```. I can not make any change to ```class B```. ```class B``` is an external library. – Rushikesh Koli May 11 '23 at 09:29
  • 2
    No, you defined `onmessage` in that object literal that you assigned to `delegate`. – trincot May 11 '23 at 09:30
  • ```delegate``` is present on ```class B``` itself. the ```onmessage``` function is present on ```delegate``` of ```class B```. I can only modify whatever is inside the ```onmessage``` function – Rushikesh Koli May 11 '23 at 09:35
  • 1
    You **assign** to `delegate`. You have full control. But hey, if you don't want to do it this way, then do it the old way, and define `that = this` just before assigning to `delegate`, and use `that` inside the `onmessage` function. – trincot May 11 '23 at 09:36
  • _“I can only modify whatever is inside the `onmessage` function”_ — Why? Are you not defining the _entire_ `class A` yourself? – Sebastian Simon May 11 '23 at 09:45
  • can you please share the code for first way you mentioned (You assign to delegate). I am not sure how to do that. @trincot – Rushikesh Koli May 11 '23 at 09:45
  • 1
    @RushikeshKoli _“You assign to delegate”_ is a factual statement about your current code, not a proposed methodology. Have you read the two linked Q&As at the top of your question? They explain everything you need to know. Also, see [How does the "this" keyword work, and when should it be used?](/q/3127429/4642212). – Sebastian Simon May 11 '23 at 09:51
  • 3
    Just define `onmessage` as an arrow function. Change your object literal to: `{ onmessage: (message) => { this.processMessage(message); } }` – trincot May 11 '23 at 09:55
  • 1
    Your mistake is doing this: `this.otherClass.delegate = { onmessage(message) {} }` which is exactly the same code as this: `this.otherClass.delegate = { onmessage: function (message) {} }`. Doing that the scope of `this` is resolved at call time. To fix it you need to do: `this.otherClass.delegate = { onmessage: (message) => {} }` – slebetman May 11 '23 at 10:06

0 Answers0