forEach中的这种情况 [英] this context in forEach
本文介绍了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
推荐答案
查看全文