У меня есть класс вроде следующего:
class SomeService {
constructor() {
this.classVar= [];
}
aFunction() {
myArray.forEach(function(obj) {
// how can I access classVar within this scope
});
}
Итак, мой вопрос в том, как я могу получить доступ к переменной classVar
внутри блока forEach
? что здесь рекомендуется?
Вы можете передать this
контекст функции forEach
:
myArray.forEach(function(obj) {
console.log(this.classVar);
}, this);
Вы можете скопировать ссылку на 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);
Array.prototype.forEach(callback[, thisArg])