如何访问匿名函数中的javascript类属性是同一个类
我有一个javascript(es2015)类,我想更新$each调用的函数中数组的值。但是,内置myarr未定义。我假设如何访问匿名函数中的javascript类属性是同一个类,javascript,class,properties,scope,Javascript,Class,Properties,Scope,我有一个javascript(es2015)类,我想更新$each调用的函数中数组的值。但是,内置myarr未定义。我假设此在中,每个函数都引用传递给每个的匿名函数。我如何访问myarr的课程设置 class mycl{ constructor(){ this.myarr=[]; } build(d){ $.each(d,function(d,i){ let myd = ..... // Do some stuff with the data
此
在中,每个
函数都引用传递给每个
的匿名函数。我如何访问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);
});
}
}
创建一个生成器函数,它是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);
});
}
}
您是否尝试过在每个函数中使用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);
}
}
push[myd]
应该是push(myd)
在每个like var self=this之前将类实例绑定到变量中@jmargolisvt。。阿纳穆尔哈桑:谢谢你的错字更正。谢谢,效果很好。