提问人:TheNormalPerson 提问时间:2/22/2023 更新时间:2/22/2023 访问量:32
Typescript - 调用类方法作为回调使用调用者的“this”上下文,而不是对象本身的类 [duplicate]
Typescript - calling class method as a callback uses "this" context of the caller and not of the class of the object itself [duplicate]
问:
我有两个简单的类:
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);
}
}
当我直接调用该方法时,一切都按预期工作,并且msg
console.log(“isRoom”,这个 Room 实例);
打印 true。
但是,当从回调调用聊天方法时
this.socket.on(“聊天”, this.room.msg);
它打印出假的并吐出
TypeError:this.castAll 不是函数
为什么?我猜我以某种方式搞砸了上下文,并且正确地得到了很多,它以某种方式接受了呼叫者的“这个”。this
我该如何解决? 为什么它真的会发生?
答: 暂无答案
评论
this.socket.on("chat", this.room.msg.bind(this.room));
应该把你整理出来......但这肯定是一个骗局。