Javascript 在匿名函数中使用变量
因此,我在使用javascript类方面没有太多经验,我面临着一个很容易解决的问题,但我找不到解决方案 很简单,我希望能够访问“.on()”匿名函数中的变量this.gtlist 我知道没有使用类的解决方案,但由于我强迫自己使用它们以便以后能够使用此代码,我面临着一堵墙Javascript 在匿名函数中使用变量,javascript,jquery,es6-class,twitch,Javascript,Jquery,Es6 Class,Twitch,因此,我在使用javascript类方面没有太多经验,我面临着一个很容易解决的问题,但我找不到解决方案 很简单,我希望能够访问“.on()”匿名函数中的变量this.gtlist 我知道没有使用类的解决方案,但由于我强迫自己使用它们以便以后能够使用此代码,我面临着一堵墙 成功:函数(流列表){ this.gtaList=[]; this.streamList=streamList for(设i=0;i,这样你就可以正确访问这个关键字了 大概是这样的: .on(“单击”,索引=>{})
成功:函数(流列表){
this.gtaList=[];
this.streamList=streamList
for(设i=0;i
我希望我已经尽可能清楚了,总的来说我觉得很难解释哈哈。使用箭头功能
=>
,这样你就可以正确访问这个
关键字了
大概是这样的:
.on(“单击”,索引=>{})
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)
}
}