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,558
  • 4
  • 36
  • 76
  • 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
  • 148,279
  • 62
  • 259
  • 315
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
  • 66,980
  • 10
  • 72
  • 94