[FEE-303] Prototypes & Inheritance
INFO
Every JavaScript object has a hidden link to another object called its prototype; property lookups walk this chain of links until a match is found or null is reached.
Context
JavaScript is one of the few mainstream languages built on prototypal inheritance rather than classical inheritance. JavaScript objects delegate property access to other objects through an internal [[Prototype]] link, and the engine follows this chain of links until it finds a match or reaches null. This mechanism underpins how method calls work, how the class syntax operates under the hood, and how built-in objects like Array and Date expose their APIs. Misunderstanding prototypes leads to accidental property shadowing, broken instanceof checks, and inheritance hierarchies that are difficult to maintain.
A concrete case shows why this matters. A library extends native Array with a custom method; the method works on arrays created in the main page but is missing on arrays created inside an iframe, even though the library code is identical in both places. Each frame runs its own global scope, so the iframe has its own Array constructor and its own Array.prototype, separate from the parent frame's. An array built inside the iframe links to the iframe's Array.prototype, and the custom method was only ever added to the parent frame's Array.prototype, so it is absent from that chain. instanceof checks against the parent frame's Array fail for the same reason: the two Array.prototype objects are not the same object. The reliable cross-realm check is Array.isArray() (see Common Mistakes below), not instanceof.
Visual
Property lookup for myObj.toString():
- Check
myObjown properties -- not found - Check
MyClass.prototype-- not found - Check
Object.prototype-- found, call it
Example
Prototype delegation with Object.create():
const animal = {
speak() {
return `${this.name} makes a sound.`;
},
};
const dog = Object.create(animal);
dog.name = 'Rex';
dog.bark = function () {
return `${this.name} barks.`;
};
dog.speak(); // "Rex makes a sound." -- delegated to animal
dog.bark(); // "Rex barks." -- own property
Object.getPrototypeOf(dog) === animal; // trueEquivalent using class syntax:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
bark() {
return `${this.name} barks.`;
}
}
const rex = new Dog('Rex');
rex.speak(); // "Rex makes a sound."
rex.bark(); // "Rex barks."
// Under the hood, the same prototype chain exists:
Object.getPrototypeOf(rex) === Dog.prototype; // true
Object.getPrototypeOf(Dog.prototype) === Animal.prototype; // trueComposition alternative (no inheritance):
function withSpeaking(obj) {
obj.speak = function () {
return `${this.name} makes a sound.`;
};
return obj;
}
function withBarking(obj) {
obj.bark = function () {
return `${this.name} barks.`;
};
return obj;
}
const rex = withBarking(withSpeaking({ name: 'Rex' }));
rex.speak(); // "Rex makes a sound."
rex.bark(); // "Rex barks."
// No prototype chain involved -- all properties are own propertiesinstanceof and Symbol.hasInstance:
class Validator {
static [Symbol.hasInstance](instance) {
return typeof instance.validate === 'function';
}
}
const form = { validate() { return true; } };
form instanceof Validator; // true -- custom check, no prototype link neededMixin pattern: adding capabilities without inheritance
// Define mixins as plain objects
const Serializable = {
serialize() {
return JSON.stringify(this);
},
deserialize(json) {
return Object.assign(Object.create(Object.getPrototypeOf(this)), JSON.parse(json));
},
};
const Validatable = {
validate() {
return Object.keys(this).every(key => this[key] !== null && this[key] !== undefined);
},
};
// Apply mixins by copying methods onto a prototype
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
Object.assign(User.prototype, Serializable, Validatable);
const user = new User('Alice', 'alice@example.com');
user.validate(); // true -- from Validatable mixin
user.serialize(); // '{"name":"Alice","email":"alice@example.com"}' -- from Serializable
// Mixins avoid the deep inheritance hierarchy problem:
// User doesn't extend SerializableValidatableBase -- it just has the methods it needsBest Practices
Prefer class syntax over manual prototype manipulation. The ES2015 class syntax produces the same prototype chain as hand-wiring Constructor.prototype, but it is substantially less error-prone. You SHOULD use class and extends for any inheritance-based design. AVOID directly assigning to Constructor.prototype or calling Object.setPrototypeOf on an object after it has been created. Mutating [[Prototype]] at runtime breaks the constructor property and confuses tooling. Per MDN, it also disrupts the optimizations engines have already made for that object's prototype chain, forcing de-optimization and recompilation. Set the prototype at creation time instead, through class/extends or Object.create.
Use Object.create(null) for pure dictionary objects. When you need a plain key-value store with no inherited behavior, SHOULD create it with Object.create(null). The resulting object has no [[Prototype]] link, so it does not inherit hasOwnProperty, toString, or any other Object.prototype method, which eliminates the risk of key collisions with inherited property names that affect ordinary object literals.
Never extend built-in prototypes in production code. Adding properties to Array.prototype, String.prototype, or any other built-in prototype constitutes monkey patching. You MUST NOT do this in production, because a future language version may add an identically-named method with a different signature, silently breaking your code. The only acceptable exception is a polyfill that guards against the method already existing.
Use instanceof and Object.getPrototypeOf for type checks. To verify that an object participates in a given prototype chain, SHOULD use instanceof (or Object.getPrototypeOf(obj) === SomeClass.prototype for single-step checks). AVOID checking for the presence of a duck-typed property when what you actually want to verify is structural identity: a property check only confirms that an interface is present, while verifying lineage requires walking the actual prototype chain.
Keep prototype chains shallow. A property lookup that misses on the instance walks every link in the chain until it finds a match or reaches null, so the cost of a miss grows with chain length. SHOULD prefer composition (mixing capabilities via plain functions or object spread) over stacking many layers of extends when the goal is sharing behavior rather than modeling a genuine is-a relationship.
Design Thinking
Why prototypal over classical? When Brendan Eich designed JavaScript in 1995, he drew heavily from the Self programming language (1986), which pioneered prototype-based object systems. Self demonstrated that object-oriented programming does not require classes: objects can delegate behavior to other objects directly. This "delegation over copying" model is simple in concept. Create an object, link it to another object, and any property not found on the first is looked up on the second. There is no separate "class" entity; objects are the only abstraction. This made JavaScript lightweight and flexible, suitable for its original role as a scripting language for the web.
The class keyword, introduced in ES2015, does not change this fundamental model. It is syntactic sugar that sets up prototype chains behind the scenes. A class Foo extends Bar statement creates Foo.prototype with [[Prototype]] pointing to Bar.prototype, exactly as manual prototype wiring would. class can look like classical inheritance from the outside. The engine still never copies a property from parent to child; every lookup that misses on the instance is a live traversal of the link class set up.
How frameworks handle component hierarchies:
React originally used class components that extend
React.Component, relying on prototype inheritance for lifecycle methods. Function components and Hooks are now the recommended default for new code, and code reuse there comes from composition (custom Hooks) rather thanextends. Class components remain fully supported and are still widespread in existing React codebases; the shift is a change of default, not a removal of class components.Vue followed a similar path. The Options API used mixins for code sharing, which suffered from name collisions and implicit dependencies, problems typical of inheritance-like patterns. The Composition API introduced composable functions as an alternative to mixins, favoring explicit composition, and both APIs remain supported side by side.
Web Components are the notable exception: custom elements must extend
HTMLElement(or a subclass). This is genuine prototype inheritance.class MyButton extends HTMLElementcreates a prototype chain linkingMyButton.prototypetoHTMLElement.prototypetoElement.prototypetoNode.prototypetoEventTarget.prototypetoObject.prototypetonull. A custom element's own methods sit alongside inherited ones fromHTMLElement.prototype, so a missingsuper()call or the wrong base class breaks the element's upgrade from a plain tag to a working component.
Deep Dive
Prototype chain lookup mechanics. When you read a property, the engine first checks whether the instance has that property as an own property. If not, it follows the [[Prototype]] link to the next object in the chain and repeats the check. This continues through the instance, its prototype, that prototype's prototype, and on up to Object.prototype and null, until a match is found or the chain is exhausted and undefined is returned. MDN notes that "trying to access nonexistent properties will always traverse the full prototype chain," making the cost of a cache miss proportional to chain depth.
Property shadowing. Setting a property directly on an instance does not modify any object in its prototype chain, as long as nothing in the chain intercepts the write. In the common case, the engine creates a new own property on the instance that "shadows" the prototype's version of that property, and reads on the instance then resolve to the own property without ever reaching the prototype. Two cases break this default. If a prototype in the chain defines an accessor (a setter) for that key, assignment invokes the inherited setter instead of creating an own property. If a prototype defines a non-writable data property for that key, the assignment is blocked (silently ignored in sloppy mode, a TypeError in strict mode). To inspect whether a given property is own or inherited, use Object.hasOwn(obj, key) (modern) or obj.hasOwnProperty(key) (legacy).
Prototype pollution. Because Object.prototype sits at the top of every ordinary object's chain, any property written to it becomes visible on every object in the runtime. Native JSON.parse does not create this risk by itself. Per the ECMAScript spec, JSON.parse has always installed parsed keys as own data properties (via [[DefineOwnProperty]], never through the [[Set]] that would invoke a prototype's setter), and this has been the specified behavior in every mainstream engine since ES5 (2009). JSON.parse('{"__proto__":{"isAdmin":true}}') therefore produces an own __proto__ property on the result object and never touches Object.prototype.
The real risk is code that takes parsed JSON (or any external object) and copies its keys through a plain assignment like obj[key] = value, most often inside a hand-written recursive merge function. If key is "__proto__", that assignment does invoke the [[Prototype]] setter and can inject properties onto Object.prototype. Non-native parsers carry the same risk directly: JSON5's parse() was vulnerable to prototype pollution via __proto__ keys before it was patched (CVE-2022-46175). A payload such as {"__proto__": {"isAdmin": true}} routed through such a merge can make every subsequent obj.isAdmin check return true. Defences include validating that key is not "__proto__", "constructor", or "prototype" before assigning; using Map instead of a plain object for any structure that accepts externally supplied keys; using Object.create(null) for accumulator objects; freezing Object.prototype itself with Object.freeze(Object.prototype); and, in Node.js, running with the --disable-proto=delete flag to remove the __proto__ accessor entirely.
// Vulnerable: naive recursive merge
function merge(target, source) {
for (const key of Object.keys(source)) {
if (typeof source[key] === 'object') {
merge(target[key], source[key]); // __proto__ assignment possible here
} else {
target[key] = source[key];
}
}
}
// Safe: key allowlist check
function safeMerge(target, source) {
for (const key of Object.keys(source)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
continue; // skip prototype-polluting keys
}
if (typeof source[key] === 'object' && source[key] !== null) {
target[key] ??= {};
safeMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
}
// Safest: use Object.create(null) as the accumulator
const config = Object.create(null);
config.theme = 'dark'; // no prototype to polluteV8 hidden classes and inline caches. JavaScript engines do not perform a raw prototype chain traversal on every property access in hot code, because that would be prohibitively slow. Instead, V8 compiles optimized machine code that assumes objects sharing the same "shape" (set of own properties in the same order) also share the same hidden class. A hidden class records the byte offset of each property, enabling O(1) property access without a hash lookup. When the engine first encounters obj.x, it generates an inline cache, a small patch of machine code that checks obj's hidden class and, if it matches, reads x directly from the cached offset.
Engines classify each access site by how many distinct hidden classes it has seen there. A monomorphic site has seen only one hidden class and is fastest, since the engine keeps a single cached offset. A polymorphic site has seen a small number of distinct shapes, so the engine keeps a short list of shape-to-offset mappings. A megamorphic site has seen so many distinct shapes that tracking them stops paying off, and the engine falls back to a generic property lookup. The practical implication: objects perform best when they are initialized with all their properties in the constructor and when properties are not deleted or added dynamically afterward, because each such mutation creates a hidden class transition. Objects that start identical but have properties added in a different order end up with different hidden classes; an access site that sees both shapes becomes polymorphic, and a site that keeps encountering new shapes beyond that degrades further to megamorphic.
// Slow: two different hidden classes despite same end state
const a = {};
a.x = 1;
a.y = 2; // hidden class: { x, y } in that order
const b = {};
b.y = 2;
b.x = 1; // hidden class: { y, x } -- different order, different class
// Fast: initialise all properties in the constructor in consistent order
class Point {
constructor(x, y) {
this.x = x; // property order locked in at construction
this.y = y;
}
}
const p1 = new Point(1, 2); // same hidden class as every other Point
const p2 = new Point(3, 4); // shares inline cache with p1Object.freeze and the prototype chain. Object.freeze(obj) makes obj's own properties non-writable and non-configurable and prevents new properties from being added. It does not freeze the prototype: any mutable property on the prototype chain is still reachable and writable. If the goal is a truly immutable value, freeze the entire chain. Call Object.freeze(obj) and Object.freeze(Object.getPrototypeOf(obj)), or use Object.create(null) with a frozen initialisation object.
const base = { shared: 'value' };
const obj = Object.create(base);
Object.freeze(obj);
obj.newProp = 'test'; // silently ignored (or throws in strict mode)
base.shared = 'mutated'; // succeeds -- base is NOT frozen
// To freeze the full chain:
Object.freeze(base);
Object.freeze(obj);
// Now both own and inherited properties are lockedCommon Mistakes
Confusing .prototype with [[Prototype]]. The .prototype property exists only on functions and is the object that becomes the [[Prototype]] of instances created with new. The [[Prototype]] internal slot exists on every object and is what the engine follows during property lookup. Object.getPrototypeOf(obj) reads [[Prototype]]; Constructor.prototype is just a regular property on the function.
Deep inheritance hierarchies become fragile. A chain like SpecialButton -> Button -> Component -> BaseComponent -> EventEmitter creates tight coupling. Changes to any intermediate prototype can break descendants in unexpected ways. Prefer composition: give objects the capabilities they need through mixins or helper functions rather than stacking layers of inheritance.
Forgetting super() in derived class constructors. In a class that extends another, the constructor must call super() before accessing this. Omitting it throws a ReferenceError. This is because the base class is responsible for creating the this object; the derived constructor only receives it after super() completes.
instanceof fails across realm boundaries. Each iframe or realm has its own global scope, including its own Array, Object, etc. An array created in an iframe is not an instanceof the parent frame's Array because the prototype chains point to different Array.prototype objects. Use Array.isArray() instead, which uses the spec-level [[IsArray]] check and works across realms.
Related Topics
- FEE-300 JavaScript Core & Runtime Overview
- FEE-301 Event Loop & Async Model
- FEE-302 Closures & Scope Chain
- [FEE-500](../Component Architecture and Design Patterns/500.md) Component Architecture Overview
References
- ECMA-262: Ordinary Object Internal Methods and Internal Slots
- MDN: Inheritance and the prototype chain
- MDN: Object.create()
- Kyle Simpson: You Don't Know JS -- this & Object Prototypes
- Axel Rauschmayer: Exploring JavaScript -- Classes
- Axel Rauschmayer: Exploring JavaScript -- Objects
- Vyacheslav Egorov (V8 team): What's up with monomorphism
- OWASP: Prototype Pollution Prevention Cheat Sheet
- snyk: Prototype Pollution
- MDN: Object.freeze()