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

Extending the Constructor Prototype

4 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 7 deck

Extending the Constructor Prototype
Fullscreen for presentation · Print / PDF for a handout
1 / 4
Lesson

Extending the Constructor Prototype

Adding shared methods to all instances efficiently.

Extending the Constructor Prototype

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
Extending the Constructor Prototype

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.
Extending the Constructor Prototype

Activity — complete the code

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