forEach()的this指向问题

请解释代码段注释的this指向?

代码段链接出处:
https://developer.mozilla.org...

function Counter() {
  this.sum = 0;
  this.count = 0;
}
Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
    ++this.count;
  }, this);//**该行的this是指向什么??**
};

var obj = new Counter();
obj.add([2, 5, 9]);
obj.count
// 3 
obj.sum
// 16
阅读 9.2k
5 个回答
Counter.prototype.add = function(array) {
  array.forEach(func, this);
};

你把第一个函数参数替换一下,this好像并没有机会指向其他对象吧

指的是 Counter 构造函数生成的实例

'用来当作callback 函数内this的值的对象',此处作为参数的this在实例化后必定指向obj啦。

指向obj(凑字数)

指向 Counter 的 实例 也就是 你定义的obj

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题