0

I have two simple classes:

 class Room{
     castAll(event: string, content: any) {
        //stuff
     }
     msg(contents: string) {
         console.log("isRoom", this instanceof Room);
         this.castAll("chat", contents);
     }
  }

class User{
  setRoom(room: Room) {
    this.room = room;
    this.mountRoomEvents();
  }
  private mountRoomEvents() {
    if (!this.room) return new Error("Mounted Room events on undefined Room");

    this.socket.on("chat", this.room.msg);
  }
}

When I call the msg method directly everything works as expected and

console.log("isRoom", this instanceof Room);

Prints True.

However when the chat method is invoked from the callback

this.socket.on("chat", this.room.msg);

It prints false and spits out

TypeError: this.castAll is not a function

Why is that? I'm guessing I somehow messed up the context and the proper this got lots and it somehow takes the `this of the caller.

How do I fix it? And why Does it actually happen?

TheNormalPerson
  • 551
  • 5
  • 15
  • 1
    `this.socket.on("chat", this.room.msg.bind(this.room));` should sort you out... but it's a dupe question for sure. – spender Feb 22 '23 at 12:04

0 Answers0