Extending the Constructor Prototype
Adding shared methods to all instances efficiently.
Extending the Constructor Prototype
Every constructor function has a prototype object. Methods added to the prototype are shared across all instances — saving memory and keeping code DRY.
- Methods on the prototype are defined once and inherited by all instances.
- Adding to the prototype after creation updates all existing instances.
- More memory-efficient than defining methods inside the constructor.
- The
classkeyword (ES6+) uses prototype inheritance internally — it is syntactic sugar.
constructor function ──▶ prototype object
▲ ▲ ▲
instance1 instance2 instance3
Prototype Extension: Code Example
function Person(name, birthdate) {
this.name = name;
this.birthdate = birthdate;
}
// Add a method to ALL Person instances
Person.prototype.calculateAge = function () {
const today = new Date();
let age = today.getFullYear() - this.birthdate.getFullYear();
const m = today.getMonth() - this.birthdate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < this.birthdate.getDate())) {
age--; // birthday not reached yet this year
}
return age;
};
const ammar = new Person('Ammar', new Date(2001, 5, 15));
const iman = new Person('Iman', new Date(2000, 10, 3));
console.log(ammar.calculateAge());
console.log(iman.calculateAge());
| Point | Detail |
|---|---|
| Constructor sets data | Properties (name, birthdate) live on each individual instance. |
| Prototype adds behaviour | calculateAge() is shared — not duplicated for each person. |
| Automatic access | Both ammar and iman can call calculateAge() via the prototype chain. |
| Dynamic extension | Adding to the prototype after objects are created still works on them. |
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the prototype extension example.
function Person(name, birthdate) {this.name = name;this.birthdate = birthdate;}// Add a method to ALL Person instancesPerson..calculateAge = function () {const today = new Date();let age = today.getFullYear() - this.birthdate.();return age;};const ammar = new Person("Ammar", new Date(2001, 5, 15));console.log(ammar.());