有一个构造器方法用于构建记录成绩的对象,对象原型中含有添加成绩,显示平均成绩的方法,对于一个数组,通过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();
请问这是什么问题呢,求解答
心有法竹
相关分类