ES2015类变量范围

时间:2017-11-30 10:02:52

标签: javascript ecmascript-6

我有一个如下课程:

classVar

所以我的问题是如何在forEach块中访问{{1}}变量?这里推荐的方法是什么?

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);