2

在这种情况下,我不知道如何保留对聊天类的引用。解决方法是什么?

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?
    }
}
4

1 回答 1

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
    }
}
于 2013-04-18T15:50:29.077 回答