Prototypes and Inheritance
Follow a property lookup up the prototype chain and explain what
classis 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
| Aspect | Classical (Java, C#) | Prototypal (JavaScript) |
|---|---|---|
| Model | Class blueprint → instance copies | Object → object delegation |
| Methods | Copied into each instance's type | Shared, found by walking the chain |
| Timing | Fixed when the class is compiled | Mutable at runtime |
| Built from | class, 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:
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 pathsWhy methods go on the prototype
An instance property holds its own copy per object. A prototype method is one function shared by every instance.
// ❌ 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; // trueA thousand instances means a thousand closures in the first form and one function in the second.
What new does
new takes four steps:
- Create an empty object.
- Set its
[[Prototype]]to the constructor's.prototype. - Run the constructor body with
thisbound to that object. - 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.
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 ownershipclass, and what it is sugar for
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; // trueBefore 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
| Scenario | Reach for | Why |
|---|---|---|
| A type with shared behaviour and many instances | class | Methods land on the prototype automatically |
| One object that should delegate to another | Object.create(proto) | Expresses delegation without inventing a class |
| Behaviour combined from several independent sources | Composition, or a mixin class expression | Single inheritance cannot express it |
| Adding a helper to arrays or strings | A standalone function | Patching 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:
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.setPrototypeOfon an existing object deoptimises it in every major engine. Set the prototype at creation time withObject.createorclassinstead.
🔑 Key Takeaways
- Property lookup walks the
[[Prototype]]chain and stops at the first match, ending atnull. classis syntax:typeofa 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.prototypeis 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.
What to Read Next
- The
thisKeyword — hownewbinding supplies the object - OOP and Composition over Inheritance — encapsulation on top of this model, and what to do when the chain stops helping