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
onmessagein that object literal that you assigned todelegate.delegate. You have full control. But hey, if you don't want to do it this way, then do it the old way, and definethat = thisjust before assigning todelegate, and usethatinside theonmessagefunction.onmessageas an arrow function. Change your object literal to:{ onmessage: (message) => { this.processMessage(message); } }this.otherClass.delegate = { onmessage(message) {} }which is exactly the same code as this:this.otherClass.delegate = { onmessage: function (message) {} }. Doing that the scope ofthisis resolved at call time. To fix it you need to do:this.otherClass.delegate = { onmessage: (message) => {} }