1

I have a class like the following:

class SomeService {

    constructor() {
        this.classVar= [];
    }

    aFunction() {
        myArray.forEach(function(obj) {
            // how can I access classVar within this scope
        });
    }

So my question is how can I access the classVar variable within forEach block? what is the recommended approach here?

Mansuro
  • 4,410
  • 4
  • 33
  • 74
  • 1
    [`Array.prototype.forEach(callback[, thisArg])`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/forEach) – Andreas Nov 30 '17 at 10:08

2 Answers2

2

You can pass this context to the forEach function:

myArray.forEach(function(obj) {
    console.log(this.classVar);
}, this);
hsz
  • 143,040
  • 58
  • 252
  • 308
1

You can copy the reference to self

class SomeService {

    constructor() {
        this.classVar= [];
    }

    aFunction(myArray) {
        var self = this; //copy this to self
        myArray.forEach(function(obj) {
           self.classVar.push(obj);
        });
    }
}

Demo

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);
gurvinder372
  • 64,240
  • 8
  • 67
  • 88