Prototypes & Inheritance
JavaScript is a prototype-based language.
Every object has an internal link to another object called its
[[Prototype]] — forming a
prototype chain through which property and method lookups travel.
Understanding this mechanism is the key to understanding
this, ES6 classes, inheritance patterns,
and why built-in methods like .toString() and
.map() are available on every object and array.
new
keyword.prototype
Object.create()
class syntax relates to
prototypes under the hoodWhat is a Prototype?
Every JavaScript object has a hidden internal property called
[[Prototype]] (accessible as
__proto__ in browsers or via
Object.getPrototypeOf()).
This prototype is itself an object — and it may also have a prototype — forming
a chain that ends at null:
name: "Rex",
breed: "Lab"
bark(), describe()
toString(),
hasOwnProperty(), valueOf()
undefined
null is reached.dog.toString(), JS doesn't find it
on dog, checks Dog.prototype, doesn't find it, checks
Object.prototype, finds it and calls it.
class syntax makes prototypes look like
classical OOP — but under the hood it still uses the same prototype chain. Classes
compile down to constructor functions + prototype assignments.How Property Lookup Works
When you access a property on an object, JavaScript
performs a lookup walk up the prototype chain.
This is what allows every object to use built-in methods like
toString() without you defining them:
dog.name // ✅ found on dog directly → "Rex"
// Step 2 — Not found? Check prototype
dog.bark() // ✅ found on Dog.prototype → called
// Step 3 — Not found? Check Object.prototype
dog.toString() // ✅ found on Object.prototype → "[object Object]"
// Step 4 — Not found anywhere → undefined
dog.fly // ❌ undefined — chain exhausted
const animal = { breathes: true, describe() { return "I am an animal"; } };
const dog = Object.create(animal); // dog.__proto__ === animal
dog.name = "Rex";
dog.breed = "Labrador";
// ── Own property lookup ──────────────────────────────────────
console.log(dog.name); // "Rex" — found on dog itself
// ── Inherited property lookup ────────────────────────────────
console.log(dog.breathes); // true — found on animal (prototype)
console.log(dog.describe()); // "I am an animal" — inherited method
// ── Object.prototype level ───────────────────────────────────
console.log(dog.toString()); // "[object Object]" — from Object.prototype
// ── Check own vs inherited ───────────────────────────────────
console.log(dog.hasOwnProperty("name")); // true — own property
console.log(dog.hasOwnProperty("breathes")); // false — inherited
// ── Inspect prototype chain ──────────────────────────────────
console.log(Object.getPrototypeOf(dog) === animal); // true
console.log(Object.getPrototypeOf(animal) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // null
// ── in operator checks entire chain ─────────────────────────
console.log("name" in dog); // true (own)
console.log("breathes" in dog); // true (inherited)
console.log("fly" in dog); // false (not in chain)
Constructor Functions & the new Keyword
Before ES6 classes, the standard pattern for creating
multiple objects with the same shape was a constructor function
called with new. Understanding this pattern
is essential because ES6 classes compile down to exactly this:
const dog = new Dog("Rex", "Lab");
// 1. Creates a blank object: {}
// 2. Sets its [[Prototype]] to Dog.prototype
// 3. Runs Dog() with "this" pointing to the new object
// 4. Returns the new object (unless Dog explicitly returns an object)
// ── Constructor function ─────────────────────────────────────
function Dog(name, breed) {
this.name = name; // own property on each instance
this.breed = breed;
}
// ── Add shared methods on the prototype ──────────────────────
// Stored ONCE, shared across ALL Dog instances
Dog.prototype.bark = function() {
console.log(`${this.name} says: Woof!`);
};
Dog.prototype.describe = function() {
return `${this.name} is a ${this.breed}`;
};
// ── Create instances with new ────────────────────────────────
const dog1 = new Dog("Rex", "Labrador");
const dog2 = new Dog("Buddy", "Poodle");
dog1.bark(); // Rex says: Woof!
dog2.bark(); // Buddy says: Woof!
console.log(dog1.describe()); // Rex is a Labrador
// ── bark is shared, not copied ───────────────────────────────
console.log(dog1.bark === dog2.bark); // true — same function reference
console.log(dog1.hasOwnProperty("bark")); // false — it's on the prototype
console.log(dog1.hasOwnProperty("name")); // true — own property
// ── instanceof ───────────────────────────────────────────────
console.log(dog1 instanceof Dog); // true
console.log(dog1 instanceof Object); // true — Dog.prototype inherits from Object.prototype
// ── constructor property ─────────────────────────────────────
console.log(dog1.constructor === Dog); // true — points back to Dognew
new is a common bug.
Without new, this is undefined (strict mode) or
the global object (sloppy mode) — and no object is returned. Always capitalise constructor
function names by convention (Dog, not dog) as a visual reminder.
Inheritance with Object.create()
Object.create(proto)
creates a new object whose [[Prototype]]
is set to proto. This is the most
direct way to set up prototype-based inheritance — no classes required,
and no constructor function magic:
// ── Base prototype object ────────────────────────────────────
const vehicleProto = {
start() { console.log(`${this.make} engine started`); },
stop() { console.log(`${this.make} engine stopped`); },
info() { return `${this.make} ${this.model} (${this.year})`; },
};
// ── Factory function using Object.create ─────────────────────
function createVehicle(make, model, year) {
const v = Object.create(vehicleProto); // prototype is vehicleProto
v.make = make;
v.model = model;
v.year = year;
return v;
}
const car1 = createVehicle("Toyota", "Camry", 2024);
const car2 = createVehicle("Honda", "City", 2023);
car1.start(); // Toyota engine started
console.log(car1.info()); // Toyota Camry (2024)
console.log(car2.info()); // Honda City (2023)
// ── child prototype inheriting from parent ───────────────────
const evProto = Object.create(vehicleProto); // inherits vehicle methods
evProto.charge = function() {
console.log(`${this.make} is charging...`);
};
function createEV(make, model, year, range) {
const ev = Object.create(evProto);
ev.make = make; ev.model = model;
ev.year = year; ev.range = range;
return ev;
}
const tesla = createEV("Tesla", "Model 3", 2024, 500);
tesla.start(); // Tesla engine started ← from vehicleProto
tesla.charge(); // Tesla is charging... ← from evProto
console.log(Object.getPrototypeOf(tesla) === evProto); // true
console.log(Object.getPrototypeOf(evProto) === vehicleProto); // truePrototypal Inheritance with Constructor Functions
Before ES6 classes, prototypal inheritance between constructor
functions was set up by manually linking prototypes with
Object.create() and calling the
parent constructor with .call().
Understanding this reveals what ES6 classes do behind the scenes:
Animal(name)
Animal.prototype
Dog(name, breed) calling
Animal.call(this, name)
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
class Animal { constructor(name) {} }
class Dog extends Animal — links prototype
chain automatically
super(name) in child constructor —
handles parent init
// ── Parent constructor ───────────────────────────────────────
function Animal(name, sound) {
this.name = name;
this.sound = sound;
}
Animal.prototype.speak = function() {
console.log(`${this.name} says ${this.sound}`);
};
Animal.prototype.toString = function() {
return `Animal(${this.name})`;
};
// ── Child constructor ────────────────────────────────────────
function Dog(name, breed) {
Animal.call(this, name, "Woof"); // 1. Call parent constructor
this.breed = breed;
}
// 2. Link Dog.prototype to Animal.prototype
Dog.prototype = Object.create(Animal.prototype);
// 3. Fix the constructor reference
Dog.prototype.constructor = Dog;
// 4. Add Dog-specific methods
Dog.prototype.fetch = function() {
console.log(`${this.name} fetches the ball!`);
};
// ── Use the inherited chain ──────────────────────────────────
const rex = new Dog("Rex", "Labrador");
rex.speak(); // Rex says Woof ← from Animal.prototype
rex.fetch(); // Rex fetches the ball! ← from Dog.prototype
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // true ← chain links correctly
console.log(rex.constructor === Dog); // true ← fixed correctlyES6 Classes — Syntactic Sugar Over Prototypes
ES6 class syntax is
clean and familiar — but it compiles down to exactly the same prototype
mechanism. The JavaScript engine still creates constructor functions and
prototype chains. There is no new inheritance model
— just a cleaner syntax for the one that already existed:
// ── ES6 class version ────────────────────────────────────────
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() { return `${this.name} says ${this.sound}`; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name, "Woof"); // calls Animal constructor
this.breed = breed;
}
fetch() { return `${this.name} fetches!`; }
}
const rex = new Dog("Rex", "Labrador");
console.log(rex.speak()); // Rex says Woof
console.log(rex.fetch()); // Rex fetches!
// ── Proof: class is still a function + prototype ─────────────
console.log(typeof Animal); // "function" — class IS a function
console.log(typeof Animal.prototype); // "object"
console.log(Animal.prototype.speak); // [Function: speak] — on the prototype
console.log(Object.getPrototypeOf(rex) === Dog.prototype); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
// ── Method overriding ────────────────────────────────────────
class GoldenRetriever extends Dog {
fetch() { return `${this.name} fetches enthusiastically!`; }
describe() { return `${super.speak()} and loves to fetch`; }
}
const buddy = new GoldenRetriever("Buddy", "Golden");
console.log(buddy.fetch()); // Buddy fetches enthusiastically!
console.log(buddy.describe()); // Buddy says Woof and loves to fetchclass in JavaScript does not create a new "class-based" system.
It is 100% syntactic sugar over constructor functions and
prototype chains. typeof Animal === "function" — always.
Methods defined in a class body are placed on
ClassName.prototype, not copied to each instance.
Prototype Approaches — Full Comparison
JavaScript offers several ways to set up prototype chains and inheritance. Here's when to use each:
| Approach | How prototype is set | Best for | Use today? |
|---|---|---|---|
| Object literal | Inherits from Object.prototype automatically |
One-off data objects, configs | ✅ Always |
| Object.create(proto) | Explicitly sets [[Prototype]] to any object |
Factory functions, prototype delegation | ✅ Yes |
| Constructor + .prototype | new sets [[Prototype]] to Fn.prototype |
Understanding internals, legacy code | ⚠️ Legacy |
| ES6 class / extends | extends wires prototype chain automatically | Modern OOP patterns, React components | ✅ Preferred |
| __proto__ direct assignment | Sets [[Prototype]] directly on any object | Nothing — slow, deprecated | ❌ Avoid |
Real-World Use Cases
Understanding prototypes is crucial in these everyday JavaScript scenarios:
class MyComp extends React.Component uses prototypal
inheritance — this.setState is inherited from
React.Component.prototype.
Array, Error, or
EventEmitter using class to add custom behaviour while
inheriting all built-in methods.
Model.findById() is on the prototype, shared across all model
instances.class ValidationError extends Error — inherits
stack, message, and all Error methods while adding custom
properties.
TypeError: x is not a function — the method wasn't on the prototype where
you expected it.
Object.assign(Target.prototype, mixin) to compose
behaviour from multiple sources when single inheritance isn't enough.Try It — Live Editor
Experiment with prototype chains, constructor functions,
Object.create(), and class-based
inheritance below.
Common Patterns & Recipes
These are the most practical prototype and inheritance patterns you'll encounter in real JavaScript codebases:
// ── Custom Error class ───────────────────────────────────────
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("Required", "email");
} catch (e) {
console.log(e instanceof ValidationError); // true
console.log(e instanceof Error); // true
console.log(e.field); // "email"
}
// ── Mixin pattern — compose multiple behaviours ──────────────
const Serializable = {
toJSON() { return JSON.stringify(this); },
fromJSON(s) { return Object.assign(this, JSON.parse(s)); },
};
const Timestamped = {
stamp() { this.updatedAt = Date.now(); return this; },
};
class User { constructor(n) { this.name = n; } }
Object.assign(User.prototype, Serializable, Timestamped);
const u = new User("Alice");
console.log(u.toJSON()); // '{"name":"Alice"}'
// ── Check prototype chain safely ─────────────────────────────
const getChain = obj => {
const chain = [];
let proto = Object.getPrototypeOf(obj);
while (proto) { chain.push(proto.constructor?.name ?? "anon"); proto = Object.getPrototypeOf(proto); }
return chain;
};
console.log(getChain(rex)); // ["Dog", "Animal", "Object"]
// ── Null prototype object (no inherited props) ───────────────
const pureMap = Object.create(null); // no toString, no hasOwnProperty etc.
pureMap.key = "value"; // perfect for safe string-key maps
dog.toString() and toString is not on
dog or Dog.prototype, where does JavaScript find it?
typeof Animal return when Animal is
defined as an ES6 class?Dog.prototype, how many copies of that
method exist in memory for 100 Dog instances?- Every JavaScript object has a hidden [[Prototype]] link forming a chain
that ends at
null. Property lookup walks this chain from instance → prototype → Object.prototype → null. - Use
Object.getPrototypeOf(obj)to safely inspect prototypes. Avoid directly reading/writing__proto__in production code. - Methods on
Constructor.prototypeare stored once and shared across all instances — far more memory-efficient than defining methods in the constructor body. - Constructor functions +
newwas the pre-ES6 way to create typed objects.newcreates a blank object, sets its [[Prototype]], runs the constructor, then returns the object. Object.create(proto)creates a new object with an explicitly set prototype — the cleanest, most direct way to set up prototype delegation.- ES5 inheritance requires:
Parent.call(this)+Child.prototype = Object.create(Parent.prototype)+Child.prototype.constructor = Child. - ES6
class / extends / superis syntactic sugar — the engine still creates constructor functions and prototype chains.typeof MyClass === "function"— always. - Methods defined in a class body land on
ClassName.prototype, not on each instance. Only properties assigned in the constructor withthis.x = ...become own properties.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.