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

10
  • 2
    No, you defined onmessage in that object literal that you assigned to delegate. Commented May 11, 2023 at 9:30
  • 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. Commented May 11, 2023 at 9:36
  • 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?. Commented May 11, 2023 at 9:51
  • 3
    Just define onmessage as an arrow function. Change your object literal to: { onmessage: (message) => { this.processMessage(message); } } Commented May 11, 2023 at 9: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) => {} } Commented May 11, 2023 at 10:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.