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

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

最佳答案

试图在类实例上保留对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
    }
}

关于typescript - typescript 无法保留对所有者类的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16087440/

10-11 12:38
查看更多