[英]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.