2Minutes: JavaScript Inheritance (Prototypes & Classes)
Most developers use JavaScript inheritance every day without realizing how the engine is actually stitching things under the hood.
We write class Admin extends User, and it feels like traditional Java or C++. But JavaScript doesn’t have classes in the traditional sense—it uses prototypes.
Let’s break down how JavaScript inheritance actually works, step by step.
The Secret Engine: Prototype Chains
When you create an object, JavaScript secretly attaches a hidden link to it (historically called __proto__).
Think of it like a family tree. When you try to call a method on an object:
- JavaScript checks the object itself.
- If it doesn’t find it, it walks up the Prototype Chain to the parent object.
- It keeps walking until it finds the property or hits
null.
Before ES6, we had to wire this up manually using constructor functions and Object.create():
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Inherit properties
}
// Link the prototype chain manually
Dog.prototype = Object.create(Animal.prototype);
const myDog = new Dog('Rex');
myDog.speak(); // Output: Rex makes a noise.That Object.create() line is where the magic happens—it tells JavaScript where to look next if a method isn’t found on the Dog.
Enter ES6 Classes: Syntactic Sugar
That manual setup used to get messy fast. So, ES6 gave us class and extends syntax.
That probably sounds like a brand-new OOP system, I know, but it’s just syntax sugar. Under the hood, the engine is still doing the exact same prototype-chain lookups.
Here is how clean it looks today:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
bark() {
console.log(`${this.name} barks!`);
}
}
const myDog = new Dog('Max');
myDog.speak(); // Inherited from Animal!The extends keyword automatically wires up the prototype chain behind the scenes, saving us from writing boilerplate code.
That’s 2Minutes Concept, see you in the next one !
Sources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
https://www.google.com/search?q=https://javascript.info/prototypal-inheritance