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.
Figure 13: Prototype Chain lookup: Object Instance -> Constructor Prototype -> Object.prototype -> null.
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!
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
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.
How does modern ES6 package prototypal inheritance into clean, familiar class syntax? Proceed to: JavaScript Classes & Object-Oriented Programming →