JavaScript Prototypes: Prototypal Inheritance & The Prototype Chain

Unlike languages like C++ or Java that utilize classical class-based inheritance, JavaScript is fundamentally prototype-based. Even the modern ES6 class keyword is simply syntactic sugar layered on top of JavaScript's underlying prototype architecture.

JavaScript Prototypal Inheritance and Prototype Chain

Figure 13: Prototype Chain lookup: Object Instance -> Constructor Prototype -> Object.prototype -> null.

Constructor Functions & Shared Prototype Methods

Attaching methods directly inside a constructor creates redundant copies in memory for every instance. Attaching methods to Constructor.prototype shares a single memory copy across all instances:

// 1. Constructor Function
function Vehicle(type, wheels) {
    this.type = type;
    this.wheels = wheels;
}

// 2. Shared Method on Prototype (Memory Efficient!)
Vehicle.prototype.describe = function() {
    return `This vehicle is a ${this.type} with ${this.wheels} wheels.`;
};

// 3. Instantiating objects with 'new'
const bike = new Vehicle("Motorcycle", 2);
const car = new Vehicle("Sedan", 4);

console.log(bike.describe()); // "This vehicle is a Motorcycle with 2 wheels."
console.log(car.describe());  // "This vehicle is a Sedan with 4 wheels."

// Both instances point to the EXACT same method in memory:
console.log(bike.describe === car.describe); // true!

Inheriting Prototypes with Object.create()

const human = {
    isLiving: true,
    breathe() {
        return "Inhaling oxygen...";
    }
};

// Create a new object inheriting from 'human' prototype:
const engineer = Object.create(human);
engineer.field = "Computer Science";

console.log(engineer.field);    // "Computer Science" (Own property)
console.log(engineer.breathe()); // "Inhaling oxygen..." (Found via Prototype Chain!)
console.log(engineer.isLiving); // true

University Exam Corner (BCA / B.Sc CS)

Exam Question: "What is at the very top of the JavaScript Prototype Chain?"

Answer: The top of the prototype chain is Object.prototype. Its prototype link (Object.prototype.__proto__) points to null, which serves as the final terminating sentinel of every prototype lookup in JavaScript.

Next Step

How does modern ES6 package prototypal inheritance into clean, familiar class syntax? Proceed to: JavaScript Classes & Object-Oriented Programming →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!