CS Fundamentals Trainer · Guides

Prototypes and classes in JavaScript: how objects inherit and what `class` really is

The prototype chain and property lookup, how new, Object.create and class relate, what class fields, private # members and super do, why mutating shared prototype data bites, and when composition beats inheritance - with every output produced by running the code in Node.

3 min read

JavaScript has no classes in the sense of Java or C#, in which a class is a blueprint that is copied into instances. It has objects that point to other objects. The class keyword, added in ES2015, is syntax on top of that model, and knowing the model makes the odd behaviours of class predictable.

The prototype chain

Every object has an internal link to another object, its prototype (read it with Object.getPrototypeOf(obj)). When you read obj.x, the engine looks at obj, then at its prototype, then at that object's prototype, and so on until it finds x or reaches null. Writing obj.x = 1 creates an own property on obj and does not touch the prototype.

const animal = { eats: true, describe() { return `eats: ${this.eats}`; } };
const dog = Object.create(animal);
dog.barks = true;
console.log(dog.describe());                          // eats: true
console.log(Object.keys(dog));                        // [ 'barks' ]
console.log('eats' in dog, dog.hasOwnProperty('eats')); // true false

describe is found on animal, but runs with this === dog because this comes from the call (see the guide on closures and this).

new and constructor functions

new F(args) does four things: creates an empty object whose prototype is F.prototype, calls F with this set to it, and returns that object (unless F returns another object).

function Point(x, y) { this.x = x; this.y = y; }
Point.prototype.norm = function () { return Math.hypot(this.x, this.y); };
const p = new Point(3, 4);
console.log(p.norm(), Object.getPrototypeOf(p) === Point.prototype);  // 5 true

Methods live once on the prototype and are shared; the data lives on each instance.

class is the same machinery

class Shape {
  #id = 1;                       // private field
  static count = 0;              // static field
  constructor(name) { this.name = name; Shape.count++; }
  describe() { return `${this.name}#${this.#id}`; }
}
class Circle extends Shape {
  constructor(r) { super('circle'); this.r = r; }
  describe() { return super.describe() + ` r=${this.r}`; }
}
const c = new Circle(2);
console.log(c.describe(), typeof Shape, Object.getPrototypeOf(Circle) === Shape);

This prints circle#1 r=2 function true. A class is a function; extends links both Circle.prototype to Shape.prototype (for instances) and Circle to Shape (so statics are inherited). Differences from a plain constructor function that matter:

Shared mutable prototype data

Because the prototype is shared, mutating an object or array that lives there changes it for every instance:

function Bag() {}
Bag.prototype.items = [];
const a = new Bag(), b = new Bag();
a.items.push('x');
console.log(b.items);    // [ 'x' ]

Put per-instance state in the constructor (or in a class field), and only functions and constants on the prototype.

Inspecting and changing prototypes

Object.getPrototypeOf, Object.setPrototypeOf and Object.create(proto) are the standard tools. Changing the prototype of an existing object (setPrototypeOf, __proto__ assignment) works but is slow in engines, because it invalidates their optimisations; set it at creation. Extending built-ins such as Array or Error with class X extends Array works, but prefer composition unless you really want an array.

Inheritance or composition

Deep hierarchies are rigid: a change at the top ripples down, and subclasses depend on the base class's internals. A common JavaScript alternative is composition: small functions or objects that you combine.

const canFly = (o) => ({ ...o, fly: () => `${o.name} flies` });
const canSwim = (o) => ({ ...o, swim: () => `${o.name} swims` });
const duck = canSwim(canFly({ name: 'duck' }));
console.log(duck.fly(), duck.swim());   // duck flies duck swims

Use class/extends for a stable "is-a" relationship with shared behaviour, and composition for "can do".

Sources

Practise this topic: JavaScript

More guides