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

44 Views Asked by At

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

There are 2 best solutions below

1
Hao Wu On BEST ANSWER

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

0
Alexander Nenashev On

Use ES6 classes and a calculated property getter:

class Student{
  constructor(name, age, grades) {
    this.name = name;
    this.age = age;
    this.grades = grades;
  }
  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();