在forEach中的这个上下文

时间:2016-10-02 04:51:09

标签: javascript foreach

我正在阅读Mozilla Documentation,但我不理解传递给该函数的this。有人可以在这里解释更多关于this参数的用法吗?

function Counter() {
  this.sum = 0;
  this.count = 0;
}

Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
    ++this.count;
  }, this); //Why is this passed here?
};

var obj = new Counter();
obj.add([2, 5, 9]);
obj.count
// 3 
obj.sum
// 16

3 个答案:

答案 0 :(得分:1)

根据Mozilla documentation

  

thisArg可选

     

执行回调时用作this的值。

还有:

  

如果向thisArg提供了forEach()参数,会在调用时将其传递给callback,以用作其this值。否则,将传递值undefined以用作其this值。 (强调补充)

thisArg传递给forEach的是绑定上下文。默认情况下,this中的forEach是全局window对象,因为undefined用于this。传递上下文允许您从该上下文访问内容。

在原型中,thisCounter构造函数,然后传递允许您设置thisforEach内的上下文。因此,this内的window不是forEach,现在是Counter,您可以访问this.sum之类的变量,否则由于上下文。

答案 1 :(得分:0)

由于函数是自包含的,你可以这样做:

function x(){
  this.test = 5
}

它只存在于函数范围内。

如果您开始嵌套函数,如果希望范围保持不变,则需要通知函数。

它与使用bind函数的行相同。

function test(){
  this.a = 4;
  var y = function(){
    this.a += 1;
  }.bind(this);
}

如果你没有绑定,例如,this.a将是未定义的,所以行this.a += 1;与说:this.a = undefined + 1

相同

但是当你绑定时,会说:this.a = 4 + 1

答案 2 :(得分:0)

您可以使用es6中的箭头功能来阻止作用域。

  

与函数相比,arrow function表达式的语法更短   表达式和不绑定它自己的,参数,超级或   new.target。



function Counter() {
  this.sum = 0;
  this.count = 0;
}

Counter.prototype.add = function(array) {
  array.forEach(entry=>{this.sum += entry;++this.count});
};

var obj = new Counter();
obj.add([2, 5, 9]);
console.log(obj);




当es5中提供的替代方法使用bind()绑定this参数或使用thisArg附带的forEach时,这很方便其他答案。

相关问题