首页 > js数组迭代方法

js数组迭代方法

有一个构造器方法用于构建记录成绩的对象,对象原型中含有添加成绩,显示平均成绩的方法,对于一个数组,通过forEach()迭代方法,传入添加成绩的方法,目的在于对没个成绩调用添加成绩方法,然而我测试,报错就是this.scores.push(score)那里can't read property 'scores' of undefined;
代码:

function Score(){
    this.scores = [];
}
Score.prototype.add = function(score){
    this.scores.push(score);
};
Score.prototype.showAverage = function(){
    let sum = this.scores.reduce(function(pre,cur){
        return pre+cur;
    });
    console.log(sum*1.0/this.scores.length);
};
let scores = [90,80,70];
let score1 = new Score();
scores.forEach(score1.add);
score1.showAverage();

请问这是什么问题呢,求解答


scores.forEach(score1.add);

改成:

scores.forEach(score1.add.bind(score1));

就好了。

因为,在

scores.forEach(score1.add);

中,存在一个赋值过程,即把score1.add赋给了forEach的内部参数的过程。所以,它相当于:

var add0 = score1.add;
scores.forEach(add0);

结果add里面的this就变成了undefined,所以报错了。

当然,你这样改也可以:

scores.forEach(function(score) {
    score1.add(score);
});

Function.prototype.bind() bind()方法会创建一个新函数,当这个新函数被调用时,它的this值是传递给bind()的第一个参数; bind 不支持IE8 可以参考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

【热门文章】
【热门文章】