📌 What is Prototypal Inheritance?
Prototypal Inheritance is a core concept in JavaScript where objects can inherit properties and methods from other objects. Unlike classical inheritance (like in Java or C++), JavaScript uses prototypes to build inheritance chains dynamically. 🔁
Note
🔍 Basic Example
Let’s start with a simple object and create another object that inherits from it using Object.create().
Creating Inheritance with Object.create
const animal = {
eats: true,
walk() {
console.log("Animal walks");
}
};
const rabbit = Object.create(animal);
console.log(rabbit.eats); // true
rabbit.walk(); // Animal walksThe rabbit object inherits both the eats property and walk() method from animal! 🐰
📚 The Prototype Chain
When you access a property or method on an object:
- JavaScript checks if it exists on the object itself.
- If not, it climbs up the prototype chain until it finds it or reaches null.
You can inspect this chain using Object.getPrototypeOf(obj) or __proto__ (legacy):
Inspecting the Prototype
console.log(Object.getPrototypeOf(rabbit) === animal); // true
console.log(rabbit.__proto__ === animal); // true (not recommended in modern code)🧠 Why Use Prototypal Inheritance?
- Allows behavior sharing between objects without duplication 🔄
- Flexible and powerful: you can inherit from any object
- Makes your code DRY and memory-efficient 💾
🛠️ Custom Example
Building a Prototype Chain
const vehicle = {
move() {
console.log("Moving...");
}
};
const car = Object.create(vehicle);
car.drive = function () {
console.log("Driving a car");
};
car.move(); // Inherited from vehicle
car.drive(); // Own methodHere, car gets access to move() through the prototype chain, even though it’s not defined on the car object directly.
⚠️ Caution with Property Overriding
If a property exists both on the child and parent, the child’s property takes precedence:
Overriding Inherited Properties
const parent = { greet: () => console.log("Hello from parent") };
const child = Object.create(parent);
child.greet = () => console.log("Hello from child");
child.greet(); // Hello from child🔁 Constructor Functions and Inheritance
You can also use constructor functions with prototypes for inheritance:
Inheritance with Constructor Functions
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(this.name + " makes a sound");
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const dog = new Dog("Max");
dog.speak(); // Max makes a sound