1

用打字稿写的,我有这个:

export class EventDiscussionPage {
    messages: any = []
    private _channel: any;
    initChat() {
      this._channel.on('messageAdded', function(message) {
        this.messages.push(message);
      }
    }
}

添加消息后,我得到cannot read property 'push' of undefined. 我想我遇到了范围问题 - 如何将消息添加到this.messages

4

2 回答 2

3

您可以使用 ES6 lambda,而不是使用闭包函数(函数闭包会导致 this 被重新分配)。

你得到类似的东西 this._channel.on('messageAdded', (message) => this.messages.push(message));

this可以在此处找到有关 Javascript 范围的更多信息如何在回调中访问正确的 `this`?

于 2017-12-11T21:13:40.303 回答
3

你有一个范围问题。使用上下文:

export class EventDiscussionPage {
    messages: any = []
    private _channel: any;
    initChat() {
      var ctx = this;
      this._channel.on('messageAdded', function(message) {
        ctx.messages.push(message);
      }
    }
}

您指的this是“_channel”,您基本上需要携带来自父级的引用才能正确调用它。

您还可以使用箭头函数语法来避免这种情况(因为它将继承父级的上下文):

export class EventDiscussionPage {
    messages: any = []
    private _channel: any;
    initChat() {
      this._channel.on('messageAdded',(message) => {
        this.messages.push(message);
      }
    }
}
于 2017-12-11T21:14:03.170 回答