[英]How can you access a javascript class property inside of an anonymous function is the same class
我有一個javascript(es2015)類,我想更新$ .each調用的函數中數組的值。 但是,在構建中,myarr是未定義的。 我認為this
是在each
函數內,它引用傳遞給each
的匿名函數。 我如何獲得myarr
的課程實例?
class mycl{
constructor(){
this.myarr=[];
}
build(d){
$.each(d,function(d,i){
let myd = ..... // Do some stuff with the data
this.myarr.push(myd);
});
}
}
您是否嘗試過在每個函數中使用bind? 像這樣:
class mycl{
constructor(){
this.myarr=[];
}
build(d){
$.each(d,function(d,i){
let myd = ..... // Do some stuff with the data
this.myarr.push[myd];
}).bind(this);
}
}
創建一個構建器函數,該函數是Mycl的函數,然后調用該函數,而不要使用anon函數。
class mycl{
constructor(){
this.myarr=[];
}
builder(d,i){
// let myd = ..... // Do some stuff with the data
this.myarr.push(myd);
},
build(d){ $.each(d,this.builder); }
}
您將需要在變量中保留對類的引用,如下所示:
class mycl{
constructor(){
this.myarr=[];
}
build(d){
const self = this; //keep a reference to the class here and use it to access class attributes.
$.each(d,function(d,i){
let myd = ..... // Do some stuff with the data
self.myarr.push(myd);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.