Skip to content

Prototypes and Inheritance ​

Follow a property lookup up the prototype chain and explain what class is actually doing underneath.

In this chapter: delegation vs classical inheritance · the prototype chain · Object.create · constructor functions · what class compiles to

💡 The Core Idea ​

JavaScript has no classes at runtime. It has objects that delegate to other objects. Every object holds a hidden link, [[Prototype]], to another object. When you read a property the object does not own, JavaScript follows that link, then the next. It stops when something matches or the chain reaches null. class is syntax over exactly this: a nicer way to build the same links.

How It Works ​

AspectClassical (Java, C#)Prototypal (JavaScript)
ModelClass blueprint → instance copiesObject → object delegation
MethodsCopied into each instance's typeShared, found by walking the chain
TimingFixed when the class is compiledMutable at runtime
Built fromclass, extends[[Prototype]] links, Object.create

The lookup ​

A property read walks the chain one link at a time and stops at the first match.

For const buddy = new Dog() where Dog extends Animal, the chain is buddy → Dog.prototype → Animal.prototype → Object.prototype → null. That is why every object has toString without anyone defining it.

Reading and setting the link:

javascript
const obj = {};

obj.__proto__;               // deprecated accessor — recognise it, don't write it
Object.getPrototypeOf(obj);  // ✅ the standard read
Object.setPrototypeOf(a, b); // ✅ the standard write — slow, so avoid it in hot paths

Why methods go on the prototype ​

An instance property holds its own copy per object. A prototype method is one function shared by every instance.

javascript
// ❌ assigning in the constructor: one greet function per instance
function PersonBad(name) { this.name = name; this.greet = function () {}; }
new PersonBad('a').greet === new PersonBad('b').greet; // false

// ✅ on the prototype: one greet function, shared
function Person(name) { this.name = name; }
Person.prototype.greet = function () { console.log(this.name); };
new Person('a').greet === new Person('b').greet; // true

A thousand instances means a thousand closures in the first form and one function in the second.

What new does ​

new takes four steps:

  1. Create an empty object.
  2. Set its [[Prototype]] to the constructor's .prototype.
  3. Run the constructor body with this bound to that object.
  4. Return the object, unless the body explicitly returns a different object.

Object.create(Person.prototype) does only the first two steps. That makes it the direct way to express delegation with no constructor at all.

typescript
const personPrototype = {
  greet(this: { name: string }): void {
    console.log(`Hello, I'm ${this.name}`);
  },
};

const alice = Object.create(personPrototype) as { name: string; greet(): void };
alice.name = 'Alice';
alice.greet(); // 'Hello, I'm Alice' — found by delegation, not ownership

class, and what it is sugar for ​

typescript
class Animal {
  constructor(public name: string) {}

  eat(): void {
    console.log(`${this.name} is eating`);
  }
}

class Dog extends Animal {
  // `extends` is what wires Dog.prototype → Animal.prototype
  override eat(): void {
    super.eat(); // reaches the shadowed prototype method
    console.log('and wagging');
  }
}

typeof Animal; // 'function' — still a function, still a prototype
Object.getPrototypeOf(new Dog('a')) === Dog.prototype; // true

Before 2015, the same result took three lines of manual wiring. The child constructor called Animal.call(this, name). Then Dog.prototype = Object.create(Animal.prototype) linked the chain. Last, Dog.prototype.constructor = Dog repaired the reference that the assignment overwrote. Recognise it in old code, but never write it.

When to Use It ​

ScenarioReach forWhy
A type with shared behaviour and many instancesclassMethods land on the prototype automatically
One object that should delegate to anotherObject.create(proto)Expresses delegation without inventing a class
Behaviour combined from several independent sourcesComposition, or a mixin class expressionSingle inheritance cannot express it
Adding a helper to arrays or stringsA standalone functionPatching a built-in prototype breaks other code

Common Mistakes ​

❌ Replacing the prototype object after instances exist. Existing instances keep the old link and lose the new methods:

typescript
Person.prototype = { greet() {} }; // ❌ old instances are stranded
Person.prototype.greet = function () {}; // ✅ add to the existing object

❌ Patching a built-in prototype. Every library on the page sees Array.prototype.first = .... It also appears in for...in and collides with future standard methods. Write first(arr) instead.

❌ Assuming a shadowed property is gone. Assigning alice.age = 25 creates an own property that hides the prototype's. After delete alice.age, the prototype value reappears.

❌ Using this before super(). In a derived constructor, this does not exist until super returns. TypeScript catches it. Plain JavaScript throws a ReferenceError at runtime.

⚠️ Object.setPrototypeOf on an existing object deoptimises it in every major engine. Set the prototype at creation time with Object.create or class instead.

🔑 Key Takeaways ​

  • Property lookup walks the [[Prototype]] chain and stops at the first match, ending at null.
  • class is syntax: typeof a class is 'function', and its methods live on .prototype.
  • Methods on the prototype are shared; methods assigned in the constructor are duplicated per instance.
  • Fn.prototype is the object instances delegate to; obj.__proto__ is the link pointing at it.
  • Assigning a property shadows the prototype's rather than replacing it.

Interview Questions ​

Q: What is the difference between prototype and __proto__?

prototype is a property on a constructor function. It holds the object its instances will delegate to. __proto__ is the delegation link on an instance. For const a = new Person(), a.__proto__ === Person.prototype. Read the link with Object.getPrototypeOf, because __proto__ is a deprecated accessor.

Q: Are ES2015 classes real classes?

No. class is syntax over constructor functions and prototypes. A class is still a function, its methods are still installed on .prototype, and extends still just links one prototype to another. It does add real rules on top. The class name sits in the TDZ (temporal dead zone) until its declaration runs, and super() must come before this. Its methods are non-enumerable and cannot be called with new. But the object model underneath is unchanged.

Q: When would you prefer Object.create to a class?

Prefer it when one object should delegate to another and a new type adds nothing. Examples are a config object that falls back to defaults, or a test double that delegates to a real implementation. Another is a prototype chain built at runtime from data. It also gives fine control through property descriptors, which class syntax does not expose.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.