I want the display() method to show the average Student.
"this" doesn’t work and I can’t imagine how to do it any other way.
here is my code.
function Student(name, age, grades) {
this.name = name;
this.age = age;
this.grades = grades;
}
Student.prototype = {
averageGrade() {
let average = 0;
let gradesSum = 0;
for (let i = 0; i < this.grades.length; i++) {
gradesSum += this.grades[i];
average = gradesSum / this.grades.length;
}
console.log(average);
},
display() {
console.log(this.name, this.age, "Average grade: ", this.average)
}
}
const student1 = new Student("John", 42, [2, 2, 2, 2]);
student1.averageGrade();
student1.display();
2
Answers
You forgot to assign
this.average
in theaverageGrade()
function:You may also use a
get
function to calculateaverage
, so you don’t need to manually call a function before using it.Use ES6 classes and a calculated property getter: