如何解决在匿名函数中使用变量 .on
所以我在使用 JavaScript 类方面没有很多经验,而且我面临一个很容易解决但我找不到解决方案的问题。
很简单,我想访问".on()"匿名函数内的变量this.gtaList。
我知道不使用类的解决方案,但由于我强迫自己使用它们以便以后能够使用此代码,因此我面临着障碍。
...
success: function(streamList) {
this.gtaList = [];
this.streamList = streamList
for (let i = 0; i < this.streamList['data'].length; i++){
if(this.streamList['data'][i]['game_id'] == 32982){
this.gtaList.push(this.streamList['data'][i]['display_name'])
this.img = $('<img id="thumbnail'+i+' " src="https://static-
cdn.jtvnw.net/previews-ttv/live_user_'+this.streamList['data'][i]
['display_name']+'-300x200.jpg">')
.on("click",(function (index) { /* I want to use this.gtaList inside this
function*/
return function (e) {
console.log(index)
new Twitch.Embed("twitch-embed-main",{
width: '80%',height: '80%',channel: this.gtaList[index],/* this.gtaList is undefined here */
autoplay: false,layout: "video",parent: ["embed.example.com","othersite.example.com"]
});
};
})(i));
$('#twitch-embed-low').append(this.img)
}
}
...
我希望我已经尽可能清楚,总的来说我觉得很难解释哈哈。
解决方法
改用箭头函数 =>
以便您可以正确访问 this
关键字
像这样:
.on("click",index => { })
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。