请解释代码段注释的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
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你把第一个函数参数替换一下,this好像并没有机会指向其他对象吧
指的是 Counter 构造函数生成的实例
'用来当作callback 函数内this的值的对象',此处作为参数的this在实例化后必定指向obj啦。
指向obj(凑字数)
指向 Counter 的 实例 也就是 你定义的obj