Prototypes & Inheritance
Prototype Chain
Every JavaScript object has a hidden [[Prototype]] (accessible via __proto__). When you access a property, JS looks up the prototype chain:
object → object.__proto__ → object.__proto__.__proto__ → ... → null
const animal = { eats: true };
const dog = Object.create(animal);
dog.barks = true;
console.log(dog.barks); // true — own property
console.log(dog.eats); // true — found on prototype
console.log(dog.flies); // undefined — not found anywhere in chain
Constructor Functions
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const ajay = new Person("Ajay");
ajay.greet(); // "Hi, I'm Ajay"
// Chain: ajay → Person.prototype → Object.prototype → null
ES6 Classes (Syntactic Sugar)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
const dog = new Dog("Rex");
dog.speak(); // "Rex barks"
// Chain: dog → Dog.prototype → Animal.prototype → Object.prototype → null
Key Methods
// Check own property
dog.hasOwnProperty("name"); // true
// Check prototype chain
"speak" in dog; // true
// Get prototype
Object.getPrototypeOf(dog); // Dog.prototype
// Create with specific prototype
const child = Object.create(parent);
// Check instance
dog instanceof Dog; // true
dog instanceof Animal; // true
__proto__ vs prototype
__proto__ | prototype | |
|---|---|---|
| What | The actual prototype link of an object | A property on constructor functions |
| Exists on | Every object | Only functions |
| Purpose | Points to parent prototype | Becomes __proto__ of instances |
ajay.__proto__ === Person.prototype; // true
Person.prototype.__proto__ === Object.prototype; // true
Key Takeaways
- Every object has a
[[Prototype]]— JS walks up this chain to find properties. - Constructor functions +
.prototype= pre-ES6 inheritance. - ES6
class/extendsis syntactic sugar over prototypes. - Use
Object.create()for clean prototype-based inheritance.