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、リモコンに「リモコンはここにあります!」という付箋を貼るようなものです。失い続けるからです。

ファット アロー ラムダ式を使用して、コールバック サイトでレキシカル '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 に答える