【问题标题】:Accessing `this` within an event listener [duplicate]在事件侦听器中访问“this”[重复]
【发布时间】:2017-12-11 21:09:18
【问题描述】:

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

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?

【问题讨论】:

  • 尝试使用箭头函数:this._channel.on('messageAdded', (message) => {
  • 好吧,这很快——而且奏效了:)。 this._channel.on('messageAdded', message => this.messages.push(message))。我想我需要更深入地研究范围以及箭头功能为何不同。请添加为答案,以便我接受 - 谢谢!
  • @ChrisRockwell This book 来自 Kyle Simpson 可能会有所帮助
  • @ChrisRockwell,简短的回答是箭头函数没有自己的this,所以在外部词法环境中寻找this。

标签: javascript scope twilio twilio-programmable-chat


【解决方案1】:

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

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

有关 Javascript 中 this 范围的更多信息可以在这里找到 How to access the correct `this` inside a callback?

【讨论】:

    【解决方案2】:

    您有一个范围界定问题。使用上下文:

    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);
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 2018-01-25
      • 2012-06-23
      • 1970-01-01
      相关资源
      最近更新 更多