Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 7

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 class keyword (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());
PointDetail
Constructor sets dataProperties (name, birthdate) live on each individual instance.
Prototype adds behaviourcalculateAge() is shared — not duplicated for each person.
Automatic accessBoth ammar and iman can call calculateAge() via the prototype chain.
Dynamic extensionAdding 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 instances
Person..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.());