Search code examples
javascriptprototypejs

How to make one method from prototype show another variable from another method


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();


Solution

  • You forgot to assign this.average in the averageGrade() function:

    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;
        }
        
        // assign parameter to instance
        this.average = average;
        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();

    You may also use a get function to calculate average, so you don't need to manually call a function before using it.

    function Student(name, age, grades) {
      this.name = name;
      this.age = age;
      this.grades = grades;
    }
    Student.prototype = {
      get average() {
        let average = 0;
        let gradesSum = 0;
        for (let i = 0; i < this.grades.length; i++) {
          gradesSum += this.grades[i];
          average = gradesSum / this.grades.length;
        }
        
        return average;
      },
      display() {
        console.log(this.name, this.age, "Average grade: ", this.average)
      }
    }
    const student1 = new Student("John", 42, [2, 2, 2, 2]);
    student1.display();