我有一个如下课程:
classVar
所以我的问题是如何在forEach
块中访问{{1}}变量?这里推荐的方法是什么?
答案 0 :(得分:1)
您可以将引用复制到self
class SomeService {
constructor() {
this.classVar= [];
}
aFunction(myArray) {
var self = this; //copy this to self
myArray.forEach(function(obj) {
self.classVar.push(obj);
});
}
}
<强>演示强>
class SomeService {
constructor() {
this.classVar = [];
}
aFunction(myArray) {
var self = this;
myArray.forEach(function(obj) {
// how can I access classVar within this scope
self.classVar.push(obj)
});
}
}
var obj = new SomeService();
obj.aFunction([1,2]);
console.log(obj);