Skip to content
jshacks.dev
Fundamentals

Prototypes and Inheritance in JavaScript Explained in Depth

Learn how JavaScript prototypes and inheritance work: the chain, constructors, classes, mixins and prototype pollution, with runnable code.

36 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and TypeScript logos.

Most languages have classes and inheritance as their object model. JavaScript has objects and a link from each object to another, and classes are a layer of syntax over that link. The difference matters whenever something behaves oddly: a method that is shared when you wanted a copy, a property that appears in a loop and should not, an instanceof that says no to an array. This guide builds the model from the bottom, with the chain first, constructor functions second and classes third, and then covers the places where the model meets the rest of the language: copying, serialization, built-in types, security and design. Every example runs on Node.js 24 as an ES module, and the output shown is from the run.

The guide is long because the topic is wide. A reader who needs only the chain can stop after the first three sections, and a reader debugging a particular problem can jump to the bug catalogue at the end. The single-topic posts on the prototype chain, on __proto__, prototype and getPrototypeOf and on classes go deeper on one piece each, and this guide ties them together.

Objects and their properties

An object is a collection of properties, each with a key that is a string or a symbol and a value. A property is either own, stored on the object, or inherited, found by following the link. The tools for telling them apart are Object.hasOwn() for own properties and in for any.

JavaScript
const settings = { theme: "dark", retries: 0 };

console.log(Object.hasOwn(settings, "theme"), "theme" in settings);
console.log(Object.hasOwn(settings, "toString"), "toString" in settings);
console.log(Object.keys(settings), Object.getOwnPropertyNames(settings));
console.log(typeof settings.toString, settings.toString === Object.prototype.toString);

for (const key in settings) {
  console.log("for in:", key);
}
Text
true true
false true
[ 'theme', 'retries' ] [ 'theme', 'retries' ]
function true
for in: theme
for in: retries

The toString method is not on settings, and it is still callable, because lookup continued up the chain and found it on Object.prototype. The rest of this guide is the explanation of that sentence. The posts on objects and property descriptors cover the properties themselves.

The prototype chain

Every object has an internal link, called its prototype, to another object or to null. When you read a property, the engine checks the object, and if the name is missing, it checks the prototype, then the prototype's prototype, until it finds the name or reaches null. That ordered sequence of objects is the chain.

JavaScript
const animal = {
  eat() {
    return `${this.name} eats`;
  },
};

const dog = Object.create(animal);
dog.bark = function () {
  return `${this.name} barks`;
};

const rex = Object.create(dog);
rex.name = "Rex";

console.log(rex.name, rex.bark(), rex.eat(), rex.fly);

function chain(value) {
  const links = [];
  for (let o = Object.getPrototypeOf(value); o !== null; o = Object.getPrototypeOf(o)) {
    links.push(o === Object.prototype ? "Object.prototype" : Object.keys(o).join(",") || "(empty)");
  }
  return links;
}

console.log(chain(rex), chain([]).length, chain(Object.create(null)));
console.log(Object.getPrototypeOf(rex) === dog, dog.isPrototypeOf(rex), animal.isPrototypeOf(rex));
Text
Rex Rex barks Rex eats undefined
[ 'bark', 'eat', 'Object.prototype' ] 2 []
true true true

Reading rex.eat went two links up, and this inside the method was rex, because the call was made on rex. That last fact is what makes sharing methods useful: one function serves every object that inherits it, and each call sees its own receiver. rex.fly ran off the end of the chain and returned undefined. An array's chain has two built-in links, and an object created with Object.create(null) has none, which is why it makes a safe dictionary.

Text
rex  -->  dog  -->  animal  -->  Object.prototype  -->  null

Reads walk the chain, writes do not

Reading goes up the chain. Writing does not. An assignment creates or updates the property on the object you assigned to, even if the name already exists higher up, and the higher one is untouched. That asymmetry is what keeps instances independent.

JavaScript
const base = { kind: "base", count: 0, tags: [] };
const a = Object.create(base);
const b = Object.create(base);

a.kind = "a's own";
a.count += 1;
a.tags.push("shared");

console.log(a.kind, b.kind, base.kind);
console.log(a.count, b.count, base.count);
console.log(a.tags, b.tags, base.tags === a.tags);
console.log(Object.hasOwn(a, "kind"), Object.hasOwn(a, "tags"));

delete a.kind;
console.log(a.kind);
Text
a's own base base
1 0 0
[ 'shared' ] [ 'shared' ] true
true false
base

The string and the number were replaced by own properties on a, which shadowed the inherited ones, and deleting the own property revealed the inherited value again. The array was different: a.tags.push did not assign anything, it read tags up the chain and mutated the shared array in place, so b and base saw the change. This is the single most common prototype bug, and it has a simple rule: never put a mutable object on a prototype and expect each instance to have its own.

Two exceptions change what a write does. A setter found on the chain runs instead of creating an own property, and a read-only property on the chain blocks the write in strict mode, as shown in the prototype chain post.

Constructor functions and prototype

Before classes, the way to make many objects with a shared chain was a constructor function. Calling a function with new creates an object whose prototype link is the function's prototype property, runs the function with this set to the new object and returns it.

JavaScript
function Dog(name) {
  this.name = name;
  this.tricks = [];
}

Dog.prototype.bark = function () {
  return `${this.name} barks`;
};

Dog.prototype.learn = function (trick) {
  this.tricks.push(trick);
  return this;
};

const rex = new Dog("Rex");
const fido = new Dog("Fido").learn("sit");

console.log(rex.bark(), fido.tricks, rex.tricks);
console.log(Object.getPrototypeOf(rex) === Dog.prototype, rex.constructor === Dog);
console.log(Object.keys(rex), rex.bark === fido.bark);
console.log(typeof Dog.prototype, Dog.prototype.constructor === Dog);
console.log(rex instanceof Dog, rex instanceof Object);
Text
Rex barks [ 'sit' ] []
true true
[ 'name', 'tricks' ] true
object true
true true

The data, name and tricks, lives on each instance because the constructor creates it per call, and the methods live once on Dog.prototype, shared by every instance. The tricks array is per instance because it was created in the constructor, which is the fix for the shared-array bug above. The names get confusing here: Dog.prototype is the object that instances link to, and Object.getPrototypeOf(rex) reads the link, which are the same object, and Dog itself has a different prototype, Function.prototype. The post on __proto__ and prototype sorts out the three names, and the usual mistake is writing rex.prototype and getting undefined.

A function called without new does not create an object, and in sloppy mode it writes to the global object, which is why constructors were capitalized by convention and why classes refuse to be called without it.

Classes are the same machinery

A class declaration creates a function with a prototype, and its methods go on that prototype. Everything above applies. What the syntax adds is a set of rules that the hand-written version never had.

JavaScript
class Animal {
  static kingdom = "animalia";

  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound`;
  }

  static create(name) {
    return new this(name);
  }
}

class Dog extends Animal {
  speak() {
    return `${super.speak()}, then barks`;
  }
}

const rex = Dog.create("Rex");

console.log(typeof Animal, typeof Dog, rex.speak());
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype);
console.log(Object.getPrototypeOf(Dog) === Animal, Dog.kingdom);
console.log(Object.keys(Animal.prototype), Object.getOwnPropertyNames(Animal.prototype));
console.log(rex instanceof Dog, rex instanceof Animal);

try {
  Animal("x");
} catch (error) {
  console.log(error.name);
}
Text
function function Rex makes a sound, then barks
true
true animalia
[] [ 'constructor', 'speak' ]
true true
TypeError

A class is a function, and the instance methods are on its prototype, as before. extends set two links. The first connects the prototype objects, so rex inherits speak from Animal.prototype when Dog.prototype lacks it. The second connects the constructors, so Dog inherits the static members of Animal, and Dog.create produced a Dog because new this used the class it was called on. The methods are not enumerable, a class cannot be called without new and the class body is always strict. The comparison with the older style is in the post on classes being functions, and static members have their own post.

Overriding and super

A subclass can override an inherited method by defining one with the same name, which shadows the parent's. super.method() calls the parent's version with the current this, and super(...) in a constructor runs the parent's constructor and is required before this can be used.

JavaScript
class Shape {
  constructor(label) {
    this.label = label;
  }

  area() {
    return 0;
  }

  describe() {
    return `${this.label} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(radius) {
    super("circle");
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius ** 2;
  }
}

class Square extends Shape {
  constructor(side) {
    super("square");
    this.side = side;
  }

  area() {
    return this.side ** 2;
  }

  describe() {
    return `[${super.describe()}]`;
  }
}

console.log([new Circle(1), new Square(2), new Shape("blob")].map((shape) => shape.describe()));

class Broken extends Shape {
  constructor() {
    try {
      this.x = 1;
    } catch (error) {
      console.log(error.name);
    }
    super("broken");
  }
}

new Broken();
Text
[
  'circle with area 3.14',
  '[square with area 4.00]',
  'blob with area 0.00'
]
ReferenceError

describe is defined once in Shape, and calls this.area(), which resolves along the chain to the subclass's override. That is polymorphism in JavaScript: no declaration, only lookup. The Square version wraps the parent's result with super.describe(). The last example shows that touching this before super() throws, because in a derived class the object does not exist until the parent constructor creates it.

instanceof and the chain

value instanceof Constructor is a chain walk. It asks whether Constructor.prototype appears anywhere in the chain of value. It does not look at how the object was made, and it can be changed.

JavaScript
function Animal() {}
function Dog() {}
Object.setPrototypeOf(Dog.prototype, Animal.prototype);

const rex = new Dog();
console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Object);

Object.setPrototypeOf(Dog.prototype, null);
console.log(rex instanceof Animal);

class Even {
  static [Symbol.hasInstance](value) {
    return Number.isInteger(value) && value % 2 === 0;
  }
}

console.log(4 instanceof Even, 5 instanceof Even);

class Duck {
  static [Symbol.hasInstance](value) {
    return typeof value?.quack === "function";
  }
}

console.log({ quack() {} } instanceof Duck, { walk() {} } instanceof Duck);
Text
true true true
false
true false
true false

Cutting the link between the two prototypes made instanceof Animal false, because the check reads the live chain. A class can take over the check with Symbol.hasInstance, which turns instanceof into a predicate, as in the duck-typing example. The check is not safe across realms, where each frame or context has its own constructors, and the post on realms explains why Array.isArray and brand checks exist.

Own versus inherited in loops, copies and JSON

Several everyday operations see only own properties, and others see inherited ones too. Knowing which is which explains why a class instance copies and serializes differently from a literal.

JavaScript
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  get length() {
    return Math.hypot(this.x, this.y);
  }

  toString() {
    return `(${this.x}, ${this.y})`;
  }
}

const point = new Point(3, 4);

console.log(Object.keys(point), JSON.stringify(point), { ...point });
console.log(point.length, `${point}`, Object.assign({}, point).length);

const inherited = Object.create({ fromProto: 1 });
inherited.own = 2;

const forIn = [];
for (const key in inherited) forIn.push(key);
console.log(forIn, Object.keys(inherited), Object.entries(inherited));
console.log(structuredClone(point), structuredClone(point) instanceof Point);
console.log(JSON.stringify(Object.create({ a: 1 }, { b: { value: 2, enumerable: true } })));
Text
[ 'x', 'y' ] {"x":3,"y":4} { x: 3, y: 4 }
5 (3, 4) undefined
[ 'own', 'fromProto' ] [ 'own' ] [ [ 'own', 2 ] ]
{ x: 3, y: 4 } false
{"b":2}

Object keys, spread, Object.assign and JSON.stringify copy own enumerable properties only, so the getter and the method on the prototype did not appear. for...in visits inherited enumerable properties as well, which is why the loop found fromProto and Object.keys did not. structuredClone returned a plain object with the data and none of the behavior. These rules are the reason a class instance does not round trip through JSON, and a toJSON() method or an explicit mapping is how to control it, as in the post on getters and setters.

The shared mutable default trap

A property on a prototype is shared, and a mutable one is shared mutably. The bug shows in classes through a field assigned on the prototype, and it is easy to write because the syntax looks like a normal assignment.

JavaScript
function Cart() {}
Cart.prototype.items = [];
Cart.prototype.add = function (item) {
  this.items.push(item);
  return this;
};

const one = new Cart().add("pen");
const two = new Cart().add("ink");
console.log(one.items, two.items, one.items === two.items);

class SafeCart {
  items = [];
  add(item) {
    this.items.push(item);
    return this;
  }
}

const three = new SafeCart().add("pen");
const four = new SafeCart().add("ink");
console.log(three.items, four.items, three.items === four.items);

const defaults = { retries: 3, headers: { accept: "json" } };
const clientA = Object.assign(Object.create(defaults), { name: "a" });
const clientB = Object.assign(Object.create(defaults), { name: "b" });
clientA.headers.accept = "text";
console.log(clientB.headers.accept, clientA.retries);
Text
[ 'pen', 'ink' ] [ 'pen', 'ink' ] true
[ 'pen' ] [ 'ink' ] false
text 3

Both carts shared one array and each saw the other's items. The class field creates a new array per instance, which is the fix. The third example is the same bug with configuration: two clients inherited one headers object, and changing it through one changed it for both. The rule is to create per-instance state in the constructor or in a field, and to share only functions and immutable data through the prototype.

Methods, this and the prototype

A method on a prototype is a shared function, and its this is whatever the call supplies. That has two consequences: the same function serves every instance, which is cheap, and a method detached from its object loses its receiver.

JavaScript
class Greeter {
  constructor(name) {
    this.name = name;
  }

  hello() {
    return `hello ${this.name}`;
  }

  helloArrow = () => `hello ${this.name}`;
}

const a = new Greeter("a");
const b = new Greeter("b");

console.log(a.hello === b.hello, a.helloArrow === b.helloArrow);
console.log(Object.hasOwn(a, "hello"), Object.hasOwn(a, "helloArrow"));

const { hello, helloArrow } = a;

try {
  hello();
} catch (error) {
  console.log(error.name);
}

console.log(helloArrow(), hello.call(b));
Text
true false
false true
TypeError
hello a hello b

The method is one function on the prototype, and the arrow field is a new function per instance that closes over its own instance. The shared method is cheaper and loses its receiver when detached. The arrow is the opposite. For event handlers on a handful of objects the arrow is convenient, and for a model class with many instances the shared method is the better choice, with bind or a wrapper at the call site. The post on the this keyword lists the four rules.

Private fields and inheritance

Private fields, written with #, are visible only inside the class body and are not inherited. A subclass cannot read a parent's private field, and two classes can use the same private name without clashing.

JavaScript
class Account {
  #balance = 0;

  constructor(opening) {
    this.#balance = opening;
  }

  get balance() {
    return this.#balance;
  }

  static isAccount(value) {
    return #balance in value;
  }
}

class Savings extends Account {
  #rate = 0.02;

  interest() {
    return this.balance * this.#rate;
  }
}

const savings = new Savings(1000);
console.log(savings.balance, savings.interest(), Account.isAccount(savings), Account.isAccount({}));

try {
  new Function("class Bad extends Account { read() { return this.#balance; } }");
} catch (error) {
  console.log(error.name);
}

console.log(Object.keys(savings), JSON.stringify(savings));
Text
1000 20 true false
SyntaxError
[] {}

The subclass used the parent's data through the public getter, and the brand check recognized an instance of the parent through the subclass. Reading the parent's private name from the subclass is a syntax error, which is stronger than a naming convention. Private fields are the right default for state that subclasses should not touch, and a protected-by-convention method is the way to let them cooperate. The full treatment is in the post on private class fields.

Subclassing built-ins

Classes can extend the built-in types, which constructor functions could not do reliably. The subclass keeps the built-in behavior and adds methods, and methods that create new objects of the same type create instances of the subclass.

JavaScript
class Stack extends Array {
  peek() {
    return this.at(-1);
  }
}

const stack = Stack.from([1, 2, 3]);
console.log(stack.peek(), stack instanceof Array, stack.map((n) => n * 2) instanceof Stack, stack.length);

class DefaultMap extends Map {
  constructor(factory, entries) {
    super(entries);
    this.factory = factory;
  }

  get(key) {
    if (!this.has(key)) this.set(key, this.factory(key));
    return super.get(key);
  }
}

const groups = new DefaultMap(() => []);
groups.get("a").push(1);
groups.get("a").push(2);
groups.get("b").push(3);
console.log([...groups], groups instanceof Map);

class HttpError extends Error {
  constructor(status, message, options) {
    super(message, options);
    this.name = "HttpError";
    this.status = status;
  }
}

const error = new HttpError(404, "not found", { cause: "route" });
console.log(error instanceof Error, error.name, error.status, error.cause, String(error));
Text
3 true true 3
[ [ 'a', [ 1, 2 ] ], [ 'b', [ 3 ] ] ] true
true HttpError 404 route HttpError: not found

The stack kept array semantics, and map returned another Stack, because built-in methods create results through the subclass constructor. The map with defaults added one method and kept the rest. The error subclass is the common case, and the post on custom errors covers cause and serialization. Two cautions apply: a subclass of Array changes what methods like filter return, which can surprise code that expects a plain array, and a subclass of a built-in with a constructor signature that differs from the parent can break those methods, since they call new this.constructor(length).

Mixins and composition

JavaScript has single inheritance, so one class has one parent. Sharing behavior across unrelated classes is done with mixins, functions that add methods, or with composition, where an object holds another object and delegates.

JavaScript
const Serializable = (Base) =>
  class extends Base {
    serialize() {
      return JSON.stringify(this);
    }
  };

const Timestamped = (Base) =>
  class extends Base {
    touch(now = 0) {
      this.updatedAt = now;
      return this;
    }
  };

class Entity {
  constructor(id) {
    this.id = id;
  }
}

class Note extends Timestamped(Serializable(Entity)) {
  constructor(id, text) {
    super(id);
    this.text = text;
  }
}

const note = new Note(1, "hello").touch(5);
console.log(note.serialize(), note instanceof Entity);

const canWalk = (state) => ({ walk: () => `${state.name} walks` });
const canSwim = (state) => ({ swim: () => `${state.name} swims` });

function createDuck(name) {
  const state = { name };
  return { ...canWalk(state), ...canSwim(state), name: () => state.name };
}

const duck = createDuck("Donald");
console.log(duck.walk(), duck.swim(), Object.keys(duck));

const logger = { prefix: "app", log(message) { return `${this.prefix}: ${message}`; } };
const service = { prefix: "svc", logger };
console.log(service.logger.log("hi"), logger.log.call(service, "hi"));
Text
{"id":1,"text":"hello","updatedAt":5} true
Donald walks Donald swims [ 'walk', 'swim', 'name' ]
app: hi svc: hi

The mixin functions each return a subclass of whatever they are given, so a chain of them builds one linear hierarchy, and the instance is still an Entity. The factory functions compose behavior without any inheritance, and the duck has walk and swim as own properties. The last lines show delegation: the logger's this is decided by the call. Composition is more flexible, because behaviors combine freely and nothing depends on a parent's internals. Inheritance is simpler when there is a true is-a relationship and the parent is small and stable.

Choosing between inheritance and composition

A rule of thumb works for most code. Use inheritance when the subclass is a kind of the parent and you want the parent's methods and its instanceof identity, and when the base class is designed for extension. Use composition when the relationship is has-a, when behaviors vary independently or when you would otherwise need to inherit from two things. A hierarchy deeper than three levels is a smell, and a base class that every change touches is a bigger one: every edit to it reaches every descendant at once.

QuestionLeans toward
Is the new type a kind of the old one?Inheritance
Do you need instanceof to work for the parent?Inheritance
Do behaviors combine in several ways?Composition
Do you inherit only to reuse code?Composition
Is the parent stable and small?Inheritance
Might the parent change often?Composition

Polymorphism without classes

Because lookup is dynamic, any object with the right method works, whatever its chain. That is duck typing, and much JavaScript is written to it: a function that calls item.render() does not care how item was made.

JavaScript
const shapes = [
  { kind: "circle", area: () => Math.PI },
  new (class Square { area() { return 4; } })(),
  Object.create({ area() { return 9; } }),
  { area: () => 0 },
];

const total = shapes.reduce((sum, shape) => sum + shape.area(), 0);
console.log(total.toFixed(4));

function render(item) {
  if (typeof item?.render !== "function") {
    throw new TypeError("item must have a render method");
  }
  return item.render();
}

console.log(render({ render: () => "plain" }), render(new (class { render() { return "class"; } })()));

try {
  render({});
} catch (error) {
  console.log(error.message);
}
Text
16.1416
plain class
item must have a render method

Four objects built four different ways all answered area(). The explicit check before calling is the guard that gives a clear error where a bare call would give "is not a function". In TypeScript an interface expresses the same contract and the compiler checks it. Reach for a base class when you need shared code, and reach for a method name when you need a shared behavior.

Symbols and the prototype

Several language features are triggered by symbol-keyed methods, and the natural home of those methods is a prototype. Defining them in a class makes every instance behave consistently.

JavaScript
class Playlist {
  #tracks;

  constructor(...tracks) {
    this.#tracks = tracks;
  }

  *[Symbol.iterator]() {
    yield* this.#tracks;
  }

  get [Symbol.toStringTag]() {
    return "Playlist";
  }

  [Symbol.toPrimitive](hint) {
    return hint === "number" ? this.#tracks.length : this.#tracks.join(", ");
  }
}

const list = new Playlist("intro", "verse", "outro");
console.log([...list], `${list}`, +list, Object.prototype.toString.call(list));
console.log(Object.getOwnPropertySymbols(Playlist.prototype).map(String));
console.log(Object.hasOwn(list, Symbol.iterator), Symbol.iterator in list);
Text
[ 'intro', 'verse', 'outro' ] intro, verse, outro 3 [object Playlist]
[
  'Symbol(Symbol.iterator)',
  'Symbol(Symbol.toStringTag)',
  'Symbol(Symbol.toPrimitive)'
]
false true

The iterator, the string tag and the conversion hook all live on the prototype, so every instance gets them, and they are visible through in and not through hasOwn. The post on symbols lists the hooks.

Prototype pollution

The prototype chain is shared state, and code that lets an attacker write to a shared prototype changes the behavior of every object that inherits from it. Prototype pollution happens when untrusted keys reach an assignment, usually in a merge or a path-setting helper, and the key is __proto__, constructor or prototype.

JavaScript
function unsafeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (typeof source[key] === "object" && source[key] !== null) {
      target[key] = unsafeMerge(target[key] ?? {}, source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
    if (typeof source[key] === "object" && source[key] !== null) {
      target[key] = safeMerge(Object.hasOwn(target, key) ? target[key] : {}, source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

const payload = JSON.parse('{"__proto__": {"isAdmin": true}, "name": "x"}');

const victim = unsafeMerge({}, payload);
console.log(victim.isAdmin, ({}).isAdmin);

delete Object.prototype.isAdmin;

const safe = safeMerge({}, payload);
console.log(safe.isAdmin, ({}).isAdmin, Object.keys(safe));

const dictionary = Object.create(null);
dictionary.__proto__ = "just a key";
console.log(Object.keys(dictionary), Object.getPrototypeOf(dictionary));

const map = new Map([["__proto__", 1]]);
console.log(map.get("__proto__"), ({}).__proto__ === Object.prototype);
Text
true true
undefined undefined [ 'name' ]
[ '__proto__' ] null
1 true

The unsafe merge read the key __proto__ as a plain property name and followed it into the real Object.prototype, which made the flag visible on every object in the process, including a fresh empty literal. The safe merge skipped the dangerous keys and copied only own data. A dictionary made with Object.create(null) treats the key as ordinary, and a Map has no such special key at all. The defenses are to avoid recursive merges of untrusted input, to skip the three keys, to prefer Map for dynamic keys, to freeze Object.prototype in hardened environments and to keep libraries updated, since this class of bug has affected many popular ones. The post on objects shows the Object.assign and spread variants.

Changing prototypes at runtime

JavaScript lets you change a prototype after creation, and extend the built-in ones. Both are possible and rarely wise. Object.setPrototypeOf on an existing object can make engines drop optimizations for it, and adding methods to Array.prototype or Object.prototype can collide with future standards or with other libraries, which is the reason a handful of old library methods were renamed before they became standard.

JavaScript
class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }
}

Temperature.prototype.toFahrenheit = function () {
  return this.celsius * 1.8 + 32;
};

const early = new Temperature(100);
console.log(early.toFahrenheit());

Object.defineProperty(Array.prototype, "second", {
  get() {
    return this[1];
  },
  configurable: true,
});

console.log([10, 20, 30].second);
for (const key in [1, 2]) console.log("for in key", key);
console.log(Object.keys(Array.prototype).includes("second"));

delete Array.prototype.second;
console.log([10, 20, 30].second);
Text
212
20
for in key 0
for in key 1
false
undefined

Adding a method to a class's prototype made it available to instances created earlier, which is the power of delegation: the lookup is live. The extension of Array.prototype worked, and because it was defined non-enumerable it did not appear in for...in, a mistake that an assignment would have made. Polyfills use this technique to add missing standard methods, and application code should not, because the day the standard adds a method with the same name and different behavior, yours silently wins or loses. If you want an array helper, a standalone function is safer.

Engine shapes, briefly

Engines optimize objects that share a shape, meaning the same properties added in the same order. A class constructor that initializes every field gives all its instances one shape, and an object whose properties are added conditionally or deleted ends up with many shapes. The effect is not visible in correctness, and it shows up as speed and memory in large collections of records. Initialize all fields in the constructor, in the same order, with a placeholder value where needed, and avoid delete. The prototype itself is also treated as stable: building the chain once and not changing it afterward keeps lookups fast.

Debugging a chain

When a method is missing or a property comes from somewhere unexpected, print the chain. The helper below shows each object's own property names in order, and it is a good first tool when reading unfamiliar code.

JavaScript
function describeChain(value) {
  const lines = [];
  let depth = 0;
  for (let o = value; o !== null; o = Object.getPrototypeOf(o), depth++) {
    const label =
      o === Object.prototype ? "Object.prototype" :
      o === Array.prototype ? "Array.prototype" :
      o === Function.prototype ? "Function.prototype" :
      o.constructor && o.constructor.prototype === o ? `${o.constructor.name}.prototype` :
      depth === 0 ? "(the value)" : "(plain object)";
    const own = Object.getOwnPropertyNames(o).filter((name) => name !== "constructor").slice(0, 4);
    lines.push(`${"  ".repeat(depth)}${label}: ${own.join(", ") || "-"}`);
  }
  return lines;
}

class Animal {
  eat() {}
}
class Dog extends Animal {
  bark() {}
}

console.log(describeChain(new Dog()).join("\n"));
console.log(describeChain(Dog).join("\n"));
Text
(the value): -
  Dog.prototype: bark
    Animal.prototype: eat
      Object.prototype: __defineGetter__, __defineSetter__, hasOwnProperty, __lookupGetter__
(the value): length, name, prototype
  (plain object): length, name, prototype
    Function.prototype: length, name, arguments, caller
      Object.prototype: __defineGetter__, __defineSetter__, hasOwnProperty, __lookupGetter__

The first chain shows the instance, Dog.prototype, Animal.prototype and Object.prototype, each with its own names. The second shows the constructor chain that carries statics: Dog, then Animal, then Function.prototype, where the helper labels Animal a plain object because it cannot tell a class from one. In a browser or in Node's inspector, expanding [[Prototype]] in the console shows the same thing. When a method is not where you expect, the chain tells you which class defines it and whether a subclass shadows it.

Testing inheritance

Tests for inheritance check the contract more than the structure. A subclass should be usable wherever the parent is, an override should call the parent when it promises to and shared state should not leak between instances.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

class Queue {
  items = [];
  push(item) {
    this.items.push(item);
    return this;
  }
  get size() {
    return this.items.length;
  }
}

class LimitedQueue extends Queue {
  constructor(limit) {
    super();
    this.limit = limit;
  }
  push(item) {
    if (this.size >= this.limit) throw new RangeError("queue full");
    return super.push(item);
  }
}

test("a subclass works where the parent is expected", () => {
  const queues = [new Queue(), new LimitedQueue(5)];
  for (const queue of queues) {
    assert.ok(queue instanceof Queue);
    assert.equal(queue.push("a").size, 1);
  }
});

test("instances do not share state", () => {
  const a = new LimitedQueue(2).push("x");
  const b = new LimitedQueue(2);
  assert.equal(b.size, 0);
  assert.notEqual(a.items, b.items);
});

test("the override enforces its limit and still calls the parent", () => {
  const queue = new LimitedQueue(1).push("a");
  assert.throws(() => queue.push("b"), RangeError);
  assert.equal(queue.size, 1);
});

Run it with node --test on Node.js 24. The first test is the substitution check, the second catches the shared-array bug and the third pins the override's behavior. Tests like these stay valid when the implementation moves from inheritance to composition, which is the sign that they test the contract and not the structure.

Accessors, receivers and read-only properties

An accessor property on a prototype behaves differently from a data property, and the difference matters because classes define their getters and setters on the prototype. When a read finds a getter on the chain, the engine calls it with this set to the object the read started from, which the specification calls the receiver. The getter does not run with the prototype as this, so one getter serves many objects and each call sees its own data. A write that finds a setter on the chain behaves the same way: the setter runs, receives the assigned value and sees the original object as this, and no own property is created unless the setter creates one. The function Reflect.get(target, key, receiver) exposes the receiver argument, which is how proxies and wrappers forward reads without losing track of who asked.

The third case is a read-only property on the chain. A data property marked non-writable on a prototype blocks assignment on every object that inherits it, and in strict code, which includes modules and class bodies, the blocked assignment throws a TypeError instead of failing silently. The way around it is to define the property on the instance with Object.defineProperty, which ignores the inherited restriction. This rule catches people who freeze a shared defaults object and later try to override one value on an object that inherits from it, and the error message points at the assignment and not at the frozen prototype, which makes it harder to trace than it should be.

JavaScript
const proto = {
  get label() {
    return `item ${this.id}`;
  },
  set label(value) {
    this.id = value.replace("item ", "");
  },
};

const first = Object.create(proto);
first.id = 1;
const second = Object.create(proto);
second.id = 2;

console.log(first.label, second.label);
first.label = "item 9";
console.log(first.id, second.id, Object.hasOwn(first, "label"));
console.log(Reflect.get(proto, "label", { id: 42 }));

const frozen = Object.create(Object.freeze({ mode: "fixed" }));

try {
  frozen.mode = "changed";
} catch (error) {
  console.log(error.name);
}

console.log(frozen.mode, Object.hasOwn(frozen, "mode"));
Object.defineProperty(frozen, "mode", { value: "own", enumerable: true });
console.log(frozen.mode, Object.hasOwn(frozen, "mode"));
Text
item 1 item 2
9 2 false
item 42
TypeError
fixed false
own true

The two instances shared one accessor and each produced its own text. The setter wrote to first.id, and first never received an own label property, so the accessor stayed on the prototype. The frozen prototype turned the override into an error and the property stayed inherited, until Object.defineProperty created an own property directly, which is allowed because it does not go through the assignment rule. Knowing which of the three cases applies, a plain data property, an accessor or a read-only property, answers most questions about an assignment that did not behave as expected.

What the descriptors say about classes and functions

Property descriptors explain several behaviors in this guide without any extra rules. Methods defined in a class body are writable and configurable and not enumerable, which is why they stay out of Object.keys and for...in. Methods assigned in the older style, Constructor.prototype.name = function, are created by ordinary assignment, so they are enumerable and show up in loops over instances. The prototype property of a class is not writable, so you cannot replace it by assignment, while the prototype property of a plain function is writable, which is what allowed the old habit of replacing it wholesale and the constructor bug in the catalogue below. Accessors defined in a class have a getter slot and a setter slot and no value or writable flag.

The descriptors also explain the order of operations when you extend shared prototypes. A property added by assignment is enumerable, and a property added with Object.defineProperty is not unless you ask for it. Libraries that must add methods to shared prototypes define them as non-enumerable to avoid breaking code that loops over keys. When a method shows up in a loop where it should not, or fails to appear where it should, read its descriptor before anything else, since the answer is almost always in one of the three flags.

JavaScript
class Counter {
  increment() {}
  get value() {
    return 0;
  }
}

const method = Object.getOwnPropertyDescriptor(Counter.prototype, "increment");
const accessor = Object.getOwnPropertyDescriptor(Counter.prototype, "value");
console.log(method.enumerable, method.writable, method.configurable);
console.log(typeof accessor.get, accessor.set, accessor.enumerable);

const classProto = Object.getOwnPropertyDescriptor(Counter, "prototype");
console.log(classProto.writable, classProto.enumerable, classProto.configurable);

function Old() {}
Old.prototype.method = function () {};
console.log(Object.getOwnPropertyDescriptor(Old.prototype, "method").enumerable);
console.log(Object.getOwnPropertyDescriptor(Old, "prototype").writable);

for (const key in new Old()) console.log("for in sees", key);
for (const key in new Counter()) console.log("never printed", key);
Text
false true true
function undefined false
false false false
true
true
for in sees method

The class method is writable and configurable and hidden from enumeration, and the class's own prototype property is locked. The function version is the opposite on both counts, so its prototype method appears in for...in and its prototype can be replaced. None of this changes how lookup works. It changes what tools such as loops, copies and serializers see, and it is the reason a class-based object and a function-based object that look alike in the console can behave differently under for...in.

The extends keyword creates two links, and the second one carries static members. A static method or field defined on the parent is found through the constructor chain, so Child.register resolves to Base.register. Static methods run with the class as this, which is why a factory such as static create() can write new this() and build the subclass when it is called on the subclass. The hazard is the same as on instance prototypes: a static field holding an array or an object belongs to the parent, and a subclass that reads it receives the parent's object, so a push through the subclass changes the parent's data. Declare the field again on the subclass when each class needs its own copy, as the example shows.

The new.target meta property gives a constructor the class that new was applied to, which is how to build an abstract base class. The check new.target === Base throws when someone instantiates the base directly and lets subclasses through. It is a runtime check, since JavaScript has no abstract keyword, and TypeScript adds a compile-time abstract modifier on top of the same idea. The check runs in the base constructor, before any subclass code, so it also works for classes several levels down.

JavaScript
class Base {
  static registry = [];

  static register(name) {
    this.registry.push(name);
    return this;
  }

  constructor() {
    if (new.target === Base) throw new TypeError("Base is abstract");
  }
}

class Child extends Base {}

Child.register("child");
console.log(Base.registry, Child.registry === Base.registry, Object.hasOwn(Child, "registry"));

class Isolated extends Base {
  static registry = [];
}

Isolated.register("own");
console.log(Base.registry, Isolated.registry);

try {
  new Base();
} catch (error) {
  console.log(error.message);
}

console.log(new Child() instanceof Base, new Isolated().constructor.name);
Text
[ 'child' ] true false
[ 'child' ] [ 'own' ]
Base is abstract
true Isolated

The registration made through Child landed in the array owned by Base, because Child has no registry of its own and the read walked the constructor chain. The subclass that declared its own field kept its data separate. The abstract check blocked the direct instantiation and allowed both subclasses. If static state is meant to be per class, the field declaration on each subclass is the explicit and readable fix, and a Map keyed by this inside the base class is the alternative when you do not want subclasses to repeat it.

What built-in methods return: Symbol.species

Array methods that build a new array, such as map, filter, slice, splice, concat, flat and flatMap, ask the receiver's constructor to make the result, through a property named Symbol.species. By default that property returns the constructor itself, so mapping over a subclass of Array gives back an instance of the subclass. This is convenient when the subclass adds behavior and risky when its constructor has a different signature, because the engine calls the constructor with a length argument, and a constructor that expects something else may throw or build a broken object. Overriding Symbol.species with a static getter that returns Array makes the results plain arrays and avoids the problem.

Promise uses the same hook for then, and RegExp and ArrayBuffer use it too. The practical advice is short. If your subclass constructor accepts the same arguments as the built-in, leave the default. If it does not, set the species to the base type, or reconsider the design and hold the array in a field, since a class that wraps an array does not inherit these obligations. Methods that never create a new collection, such as push and sort in place, are unaffected, and the failure appears only on the first call that does.

JavaScript
class Tags extends Array {
  static get [Symbol.species]() {
    return Array;
  }

  first() {
    return this[0];
  }
}

const tags = Tags.from(["a", "b", "c"]);
const filtered = tags.filter(Boolean);
console.log(tags.first(), tags instanceof Tags, filtered instanceof Tags, Array.isArray(filtered));

class Keeps extends Array {}
console.log(Keeps.from([1, 2]).map((n) => n) instanceof Keeps);

class Strict extends Array {
  constructor(label) {
    super();
    if (typeof label !== "string") throw new TypeError("label required");
    this.label = label;
  }
}

const strict = new Strict("ok");
strict.push(1, 2);
console.log(strict.length, strict.label);

try {
  strict.map((n) => n);
} catch (error) {
  console.log(error.name, error.message);
}
Text
a true false true
true
2 ok
TypeError label required

The first subclass kept its own methods and returned plain arrays from filter. The second kept its type through map. The third built fine and failed on the first map, because the engine called new Strict(2) and the constructor rejected a number. The failure appears far from the class definition, which is why a subclass with a custom constructor should either set the species or avoid the problem by composition.

Moving a prototype hierarchy to classes

Older code builds inheritance by hand, and the translation to classes follows a fixed pattern. The child constructor calls the parent constructor with Parent.call(this, ...), which becomes super(...). The line Child.prototype = Object.create(Parent.prototype), with a restored constructor, becomes extends. The line that links the constructors for statics, Object.setPrototypeOf(Child, Parent), is also covered by extends. Methods assigned to the prototype move into the class body, where they stop being enumerable.

Three behaviors change in the move, and each deserves a check before you merge the conversion. First, a class cannot be called without new, so any code that calls a constructor as a plain function, or with .call on an existing object, now throws. Second, class declarations are not initialized before their line runs, so a reference earlier in the file raises a ReferenceError, where a function declaration would have been available. Third, the methods become non-enumerable, which changes the output of for...in and of libraries that copy enumerable properties from a prototype. If none of these is a problem in your code, the conversion is mechanical, and the structure of the chain is identical.

JavaScript
function Vehicle(wheels) {
  this.wheels = wheels;
}
Vehicle.prototype.describe = function () {
  return `${this.constructor.name} with ${this.wheels} wheels`;
};

function Bike() {
  Vehicle.call(this, 2);
}
Bike.prototype = Object.create(Vehicle.prototype, {
  constructor: { value: Bike, writable: true, configurable: true },
});
Bike.prototype.ring = function () {
  return "ring";
};
Object.setPrototypeOf(Bike, Vehicle);

class Vehicle2 {
  constructor(wheels) {
    this.wheels = wheels;
  }
  describe() {
    return `${this.constructor.name} with ${this.wheels} wheels`;
  }
}

class Car extends Vehicle2 {
  constructor() {
    super(4);
  }
  honk() {
    return "honk";
  }
}

const bike = new Bike();
const car = new Car();
console.log(bike.describe(), "|", car.describe());
console.log(bike instanceof Vehicle, car instanceof Vehicle2);
console.log(Object.getPrototypeOf(Bike.prototype) === Vehicle.prototype);
console.log(Object.getPrototypeOf(Car.prototype) === Vehicle2.prototype);
console.log(Object.getPrototypeOf(Bike) === Vehicle, Object.getPrototypeOf(Car) === Vehicle2);
console.log(Object.keys(Bike.prototype), Object.keys(Car.prototype));

try {
  Car();
} catch (error) {
  console.log(error.name);
}

console.log(new Hoisted() instanceof Hoisted);

try {
  new Later();
} catch (error) {
  console.log(error.name);
}

function Hoisted() {}
class Later {}
Text
Bike with 2 wheels | Car with 4 wheels
true true
true
true
true true
[ 'ring' ] []
TypeError
true
ReferenceError

Both hierarchies produced the same descriptions and passed the same instanceof checks, and both set the prototype link and the constructor link. The visible differences are the enumerable ring method, the error from calling the class without new and the ReferenceError for the class used before its declaration, while the function declaration was usable earlier. These are the three things to look for in a conversion.

Copying instances without losing the chain

Several copy operations drop the prototype, and the result is a plain object with the data and none of the behavior. Spread, Object.assign into a literal and structuredClone all return plain objects, as shown earlier. When you need a copy that is still an instance of the class, create the new object with the same prototype and copy the descriptors, which also preserves accessors and non-enumerable own properties that spread would drop or evaluate.

A more maintainable option is to give the class a method that builds the copy, so the class controls its own invariants. A with style method that returns a new instance with one field changed is common for immutable value objects, and it avoids the question of which copy technique is correct, since the class knows. Private fields cannot be copied by any of the generic techniques, because they are not properties, so a class that uses them needs its own copy method.

JavaScript
class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }

  format() {
    return `${this.amount} ${this.currency}`;
  }

  withAmount(amount) {
    return new Money(amount, this.currency);
  }
}

const price = new Money(5, "USD");
const spread = { ...price };
const structured = structuredClone(price);
const cloned = Object.create(Object.getPrototypeOf(price), Object.getOwnPropertyDescriptors(price));

console.log(typeof spread.format, typeof structured.format, typeof cloned.format);
console.log(cloned instanceof Money, cloned !== price, cloned.format());
console.log(price.withAmount(9).format(), price.format());

class Secret {
  #value = 1;
  read() {
    return this.#value;
  }
}

const copy = Object.create(Object.getPrototypeOf(new Secret()));

try {
  copy.read();
} catch (error) {
  console.log(error.name);
}
Text
undefined undefined function
true true 5 USD
9 USD 5 USD
TypeError

Spread and structuredClone lost the method. The descriptor-based copy kept the chain, so format worked and the instanceof check passed. The withAmount method is the version that scales, since it uses the constructor and so respects whatever the class does to its fields. The last case shows why private fields need a purpose-built copy: an object created with the right prototype but without running the constructor has no private slot, and the first method call that reads it throws.

Questions that come up in review

Should a new project use classes or plain objects? Use plain objects and functions until you have state and behavior that belong together and many instances of it, and then use a class. The two are not rivals: a class is the tidy way to attach shared functions to the data they work on, and a module of plain functions is often simpler where there is no state. Does extends ever need more than one level? It can, and the cost grows with each level, because a change to an upper class reaches every class below it. Two levels is common, three needs a reason, and a deeper tree usually wants composition.

Why does instanceof sometimes give the wrong answer for values that crossed a boundary? Because the check compares against a specific constructor, and a value that came from another frame, a worker's structured clone or a separately loaded copy of a library was built by a different constructor, even when the class looks identical. Use brand checks, Array.isArray, Symbol.hasInstance or a method-based test, and avoid relying on the identity of a class across module copies. Is Object.setPrototypeOf bad? It is legal and sometimes useful, in a polyfill or when building a chain by hand, and it is slow when applied to objects that are already in use, since engines optimize on the assumption that the chain is stable. Set the prototype at creation with Object.create or extends, and avoid changing it later.

Do private fields and the chain interact? They do not interact at all: private names belong to the class that declares them and do not follow the chain, which is why a subclass cannot read them and why the brand check #field in value is the right way to ask whether an object was built by a given constructor. Is it safe to add methods to a built-in prototype? Only in a polyfill that implements a standard behavior and checks that the method is missing first. For application code a standalone function or a subclass is safer, since a later standard method of the same name would conflict with yours.

A catalogue of prototype bugs

SymptomCauseFix
Two instances share and change the same arrayA mutable object on the prototypeCreate it in the constructor or a class field
rex.prototype is undefinedprototype exists only on functionsUse Object.getPrototypeOf(rex)
A method has the wrong this after detachingA shared method called without a receiverArrow field, bind or a wrapper
for...in lists unexpected keysIt visits inherited enumerable propertiesUse Object.keys() or Object.entries()
instanceof Array is false for an arrayThe value is from another realmUse Array.isArray()
A class instance loses its methods in JSON or cloneThose operations copy own data onlyAdd toJSON() or rebuild the class
constructor points at Object after reassigning prototypeThe default prototype was replacedAdd the constructor property, or mutate the existing prototype
An attacker's flag appears on every objectPrototype pollution through a mergeSkip __proto__, use Map, avoid recursive merges of input
ReferenceError before this in a subclass constructorsuper() not called firstCall super() before using this
A subclass static is missingThe constructor link was not setUse extends, or Object.setPrototypeOf(Sub, Base)
JavaScript
function Legacy() {}
Legacy.prototype = { hello() { return "hi"; } };
const legacy = new Legacy();
console.log(legacy.constructor === Legacy, legacy.constructor === Object, legacy instanceof Legacy);

function Fixed() {}
Fixed.prototype = { constructor: Fixed, hello() { return "hi"; } };
console.log(new Fixed().constructor === Fixed);

console.log(typeof new Legacy().prototype, Object.getPrototypeOf(new Legacy()) === Legacy.prototype);
Text
false true true
true
undefined true

The first lines are the constructor row of the table: replacing prototype with a new object drops the back link, and instanceof still works because it reads the chain and not the property. Adding constructor back fixes it.

Where this model stops

The chain describes property lookup and nothing else. It does not copy, so a prototype's change is live for every descendant, which is both the feature and the hazard. It does not provide privacy, which is what # fields and closures are for. It does not give multiple inheritance, which mixins and composition simulate. And class syntax is a layer over the chain, not a replacement: when you debug an unexpected method, the chain is what you inspect. Most application code, a service, a component, a script, can be written with plain objects and functions, and classes earn their place where there is state and behavior that belong together and many instances.

The model is defined in the specification under ordinary object internal methods and class definitions, and MDN's guide to inheritance and the prototype chain and its classes reference are the readable companions.

Also inPatterns
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.