forEach中的这种情况 [英] this context in forEach

查看:71
本文介绍了forEach中的这种情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Mozilla文档,但我不理解传递给函数的this.任何人都可以在这里解释有关this参数用法的更多信息吗?

I was reading the Mozilla Documentation, but I don't understand the this which is passed into the function. Could anyone explain more about the usage of the this argument here?

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

推荐答案

每个

thisArg可选

执行回调时用作this的值.

还有:

如果为forEach()提供了thisArg参数,则调用时它将传递给callback以用作其this值.否则,值为undefined将作为其this值使用. (添加了强调)

If a thisArg parameter is provided to forEach(), it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. (Emphasis added)

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

What passing the thisArg to forEach does is bind the context. By default, this in forEach is the global window object, because undefined is used for this. Passing the context permits you to access things from that context.

在原型中,thisCounter构造函数,然后通过它可以设置thisforEach内部的上下文.因此,它不再是forEach内的window,而是现在是Counter,并且您可以访问诸如this.sum之类的变量,否则由于上下文而无法使用.

In the prototype, this is the Counter constructor, and passing then allows you to set the context of which this is inside the forEach. So, instead of this being window inside the forEach, it is now Counter, and you can access variables such as this.sum otherwise not available due to the context.

这篇关于forEach中的这种情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆