LearnFrenzy
Sign in Take a free test

Objects · Objects Coding Problems · Question 9

Constructor function with a prototype method in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Create Student objects with a constructor function, put a shared report() method on the prototype, and show that the method is not copied into each object.

Solution
main.js
function Student(name, marks) {
  this.name = name;            // own properties, set by new
  this.marks = marks;
}
Student.prototype.report = function () {   // one shared copy for all students
  const avg = this.marks.reduce((a, b) => a + b, 0) / this.marks.length;
  return `${this.name}: average ${avg.toFixed(1)}`;
};

const s1 = new Student("Asha", [88, 92, 79]);
const s2 = new Student("Ravi", [65, 70, 72]);
console.log(s1.report());
console.log(s2.report());
console.log(Object.hasOwn(s1, "report"), s1.report === s2.report, s1 instanceof Student);

Output Verified by running it on Node.js

Asha: average 86.3
Ravi: average 69.0
false true true

new creates an object whose prototype is Student.prototype and runs the constructor with this bound to it. report lives once on the prototype and is found through the chain. Classes (ES6 Features topic) are syntax for exactly this.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links