【发布时间】: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