Tutorials JavaScript Prototypes & Inheritance
Ch 38 / 78
Chapter 38 Intermediate 10 min read JavaScript

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.

What you'll learn
What a prototype is and how the prototype chain works
How property lookup traverses the chain — own → prototype → Object.prototype → null
Constructor functions and the new keyword
Adding shared methods via .prototype
Prototype-based inheritance with Object.create()
How ES6 class syntax relates to prototypes under the hood

What 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:

dog  (instance)
Own properties: name: "Rex", breed: "Lab"
[[Prototype]] / __proto__
Dog.prototype  (constructor prototype)
Shared methods: bark(), describe()
[[Prototype]]
Object.prototype  (root)
Built-in methods: toString(), hasOwnProperty(), valueOf()
[[Prototype]]
null  (chain ends here)
No more prototypes — property lookup stops, returns undefined
[[Prototype]] / __proto__
Every object has this hidden link to its prototype. When you look up a property, JS first checks the object itself, then walks up the chain until the property is found or null is reached.
Prototype-based Inheritance
Objects inherit properties and methods from their prototype. Shared methods are stored once on the prototype — not copied to every instance — saving memory and enabling polymorphism.
Prototype Chain Lookup
When you access dog.toString(), JS doesn't find it on dog, checks Dog.prototype, doesn't find it, checks Object.prototype, finds it and calls it.
Classes Are Syntactic Sugar
ES6 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:

// Step 1 — Check the object itself
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
Own properties — checked first, fastest Prototype properties — shared, not copied Object.prototype — available on all objects null — chain ends, returns undefined
JavaScript — Prototype Chain & Lookup
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:

// What "new" does step-by-step:
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)
new — creates blank object + sets prototype this — refers to the newly created object inside the constructor Dog.prototype — where shared methods live Returned automatically — no return needed
JavaScript — Constructor Functions
// ── 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 Dog
Always use new
Calling a constructor function without 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:

JavaScript — Object.create() Inheritance
// ── 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); // true

Prototypal 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:

ES5 — Manual Setup
1 Define parent constructor Animal(name)
2 Add shared methods to Animal.prototype
3 Define child Dog(name, breed) calling Animal.call(this, name)
4 Link: Dog.prototype = Object.create(Animal.prototype)
5 Repair constructor: Dog.prototype.constructor = Dog
ES6 — class / extends
1 Define parent class Animal { constructor(name) {} }
2 Add methods as class body methods
3 class Dog extends Animal — links prototype chain automatically
4 Call super(name) in child constructor — handles parent init
5 Constructor repair happens automatically
JavaScript — ES5 Prototypal Inheritance
// ── 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 correctly

ES6 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:

JavaScript — class syntax vs prototype (equivalent)
// ── 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 fetch
Key insight
class 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:

React Class Components
class MyComp extends React.Component uses prototypal inheritance — this.setState is inherited from React.Component.prototype.
Extending Built-ins
Extend Array, Error, or EventEmitter using class to add custom behaviour while inheriting all built-in methods.
ORM / Model Classes
Database models (Mongoose, Sequelize) use class-based prototypal inheritance — Model.findById() is on the prototype, shared across all model instances.
Custom Error Classes
class ValidationError extends Error — inherits stack, message, and all Error methods while adding custom properties.
Debugging & Inspection
Understanding the chain helps debug TypeError: x is not a function — the method wasn't on the prototype where you expected it.
Mixins / Composition
Use Object.assign(Target.prototype, mixin) to compose behaviour from multiple sources when single inheritance isn't enough.
⚡
Free Resource
Download our JavaScript Cheat Sheet
Prototypes, classes, inheritance & OOP patterns — all on one page.
Get Sheet

Try It — Live Editor

Experiment with prototype chains, constructor functions, Object.create(), and class-based inheritance below.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are the most practical prototype and inheritance patterns you'll encounter in real JavaScript codebases:

JavaScript — Prototype Recipes
// ── 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
Quick Check
When you call dog.toString() and toString is not on dog or Dog.prototype, where does JavaScript find it?
Quick Check
What does typeof Animal return when Animal is defined as an ES6 class?
Quick Check
If a method is defined on Dog.prototype, how many copies of that method exist in memory for 100 Dog instances?
Chapter Summary
  • 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.prototype are stored once and shared across all instances — far more memory-efficient than defining methods in the constructor body.
  • Constructor functions + new was the pre-ES6 way to create typed objects. new creates 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 / super is 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 with this.x = ... become own properties.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel