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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!