在这种情况下,我无法弄清楚如何保持对聊天课程的引用。什么是解决方法?
class chat {
private self: chat;
public currentUsers: any = ko.observableArray();
constructor(public chatService: any) {
this.self = this;
chatService.client.receiveUsers = this.receiveUsers;
}
private receiveUsers(users: any): void {
//'this' has been changed to refer to the external caller context (chatService.client)
this.currentUsers(users);//fail
//property currentUsers does not exist on value of type 'Window'
self.currentUsers(users);//fail
//currentUsers does not exist in the current scope
currentUsers(users);//fail
//There's apparently no way to access anthing in this chat class from inside here?
}
}
答案 0 :(得分:4)
尝试在类实例上保留对this
的引用就像在遥控器上添加一个粘滞便笺,上面写着“这就是遥控器的位置!”因为你一直在失去它。
使用胖箭头lambda表达式捕获回调站点上的词汇'this':
class chat {
public currentUsers: any = ko.observableArray();
constructor(public chatService: any) {
chatService.client.receiveUsers = (users) => this.receiveUsers(users);
}
private receiveUsers(users: any): void {
// use 'this' here now
}
}