In JavaScript, inheritance doesn’t work like it does in traditional class-based languages. Instead of copying properties from one class to another, JavaScript uses prototypal inheritance, where objects delegate behavior to other objects through a chain.
Let’s explore how this works using real examples.
🧠 What is prototypal inheritance?
Every object in JavaScript can be linked to another object called its prototype. When you try to access a property or method on an object:
- JavaScript looks for it directly on the object.
- If it doesn’t find it, it climbs up the prototype chain.
🧰 Example 1: tool inheritance
const tool = {
use() {
return 'This tool is being used';
}
};
const hammer = {
type: 'Hammer'
};
Object.setPrototypeOf(hammer, tool);
console.log(hammer.use()); // "This tool is being used"
console.log(hammer.type); // "Hammer"
console.log(hammer.hasOwnProperty('use')); // false
hammer
inherits theuse
method fromtool
- It doesn’t copy the method; it delegates to
tool
🐾 Example 2: animal behaviors
const animal = {
walk() {
return 'Moving forward';
}
};
const dog = Object.create(animal);
dog.bark = function () {
return 'Woof!';
};
const pet = Object.create(dog);
pet.name = 'Pedro';
console.log(pet.walk()); // "Moving forward"
console.log(pet.bark()); // "Woof!"
console.log(pet.name); // "Pedro"
pet
→ inherits fromdog
dog
→ inherits fromanimal
pet
can access everything up the chain
🧪 Example 3: lab equipment
function Equipment(serial) {
this.serial = serial;
}
Equipment.prototype.inspect = function () {
return 'Inspection passed';
};
const microscope = new Equipment('PX-001');
console.log(microscope.serial); // "PX-001"
console.log(microscope.inspect()); // "Inspection passed"
- The
inspect
method lives inEquipment.prototype
microscope
delegates the method call through the prototype
📦 Example 4: permissions and roles
const role = {
canAccessPanel: false
};
const admin = Object.create(role);
admin.canAccessPanel = true;
admin.canDeleteUsers = true;
const pedro = Object.create(admin);
pedro.username = 'pedro123';
console.log(pedro.canAccessPanel); // true
console.log(pedro.canDeleteUsers); // true
console.log(pedro.username); // "pedro123"
pedro
inherits permissions fromadmin
admin
inherits fromrole
- Prototypal inheritance creates layered behavior
📌 Recap
- Objects in JavaScript can delegate behavior to other objects via their prototype
- Use
Object.create()
or constructor functions to create inheritance chains - The prototype chain is searched top-down whenever a property is accessed
- Prototypes are great for reusing behavior across objects without duplication
✅ Conclusions
Prototypal inheritance is JavaScript’s way of sharing functionality. Instead of copying behavior from one object to another, objects pass responsibility up the chain.
This approach makes your code flexible, efficient, and expressive—whether you're modeling tools, animals, roles, or anything else.