javascript - forEach()的this指向问题
本文介绍了javascript - 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
解决方案
Counter.prototype.add = function(array) {
array.forEach(func, this);
};
你把第一个函数参数替换一下,this好像并没有机会指向其他对象吧
这篇关于javascript - forEach()的this指向问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文