Skip to content

Prototypes: The Object Model Behind JavaScript Classes

class in ES2015 is essentially syntactic sugar over prototypes: if you understand the [[Prototype]] chain, Object.create, and the new sequence, you debug this errors and shared methods with more confidence.

≈ 11 min readSoftwareFrontend
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return this.name + ' makes a sound';
  }
}

const minka = new Animal('Minka');
const rex = new Animal('Rex');

minka.speak === rex.speak;                         // true
minka.hasOwnProperty('speak');                     // false
Object.getPrototypeOf(minka) === Animal.prototype; // true

Three lines of output, and the whole article is in them. The method speak exists exactly once, even though two instances call it. Neither instance owns it – hasOwnProperty says no. It is found on a third object, Animal.prototype, which both instances point to with an internal reference.

class didn’t invent this third object; it just moved it out of sight. In JavaScript, the reference to it carries every method lookup, every inheritance relationship, and every lost this binding. That is why I build up the model from the bottom here: first plain prototypes with Object.create, then constructor functions and the new sequence, then class as the facade that combines both.

The foundation is surprisingly simple. Every object in JavaScript carries an internal reference, called [[Prototype]] in the specification. This reference points either to another object – the prototype – or to null. When you access a property that the object itself doesn’t have, the language doesn’t give up and return undefined. It first follows the [[Prototype]] link and keeps searching there. And if it finds nothing there, it goes one link higher. That is how the prototype chain comes about, and it ends at null.

You see this most clearly without any class and without new, using only Object.create:

const animal = {
  describe() {
    return this.name + ' makes ' + this.sound;
  }
};

const dog = Object.create(animal);
dog.name = 'Rex';
dog.sound = 'woof';

dog.describe(); // 'Rex makes woof'

Object.getPrototypeOf(dog) === animal; // true
dog.hasOwnProperty('describe');        // false
dog.hasOwnProperty('name');            // true

Look at what happens here. The object dog itself only owns name and sound – hasOwnProperty confirms that. It doesn’t find the method describe on itself but only one step higher, on animal. During the call, though, what counts is who the receiver was: this is dog, which is why describe reads Rex and woof. The method lives on the prototype, the data lives on the instance, and the lookup connects the two. That is the whole mechanism – no classes, no constructors, just one object pointing to another.

Object.create makes this link explicitly visible: the first parameter becomes the new object’s [[Prototype]] directly. You can even write Object.create(null) and get an object with no prototype at all – no toString, no hasOwnProperty, a bare dictionary. Useful when you want an object as a pure key-value store and don’t want inherited properties getting in the way.

The chain, visualized#

When dog.describe() is called, the lookup walks up the chain. The following diagram shows the stations up to the end at null:

graph TD
  A["dog<br/>own: name, sound"] -->|"[[Prototype]]"| B["animal<br/>own: describe"]
  B -->|"[[Prototype]]"| C["Object.prototype<br/>own: hasOwnProperty, toString"]
  C -->|"[[Prototype]]"| D["null"]

Every arrow is a [[Prototype]] reference, and the lookup climbs along them. If the language looks for describe, it finds it at animal. If it were looking for toString, it would go one station further to Object.prototype. And if it were looking for something that exists nowhere, it would arrive at null and return undefined. This chain is not a special case for hand-built objects – every object, every array, every function hangs on a chain like this, with Object.prototype at its root.

Constructor functions: the way before class#

Before ES2015, you built reusable “types” with constructor functions. The trick lies in two parts that you have to keep apart. First: every function has a property called prototype – an ordinary object that serves as a template. Second: the new operator connects a fresh object to exactly this template.

function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  return this.name + ' makes a sound';
};

const cat = new Animal('Minka');
cat.speak(); // 'Minka makes a sound'

Object.getPrototypeOf(cat) === Animal.prototype; // true
cat.hasOwnProperty('speak');                     // false

What exactly does new Animal('Minka') do? The sequence has – simplified – three steps. First, a new, empty object is created, and its [[Prototype]] is set to Animal.prototype. Then Animal is called with this pointing to this new object – that is how this.name = name ends up as an own property on the instance. And finally: if the function itself doesn’t return an object, the new object becomes the result. That is why speak isn’t on the instance but on Animal.prototype, and is shared by all cats.

Before class, inheritance was manual work – and precisely this manual work shows what extends later automates:

function Dog(name) {
  Animal.call(this, name);       // Parent-Konstruktor auf eigenem this
}

Dog.prototype = Object.create(Animal.prototype); // Kette einhängen
Dog.prototype.constructor = Dog;                 // constructor wieder setzen

Dog.prototype.speak = function () {
  return this.name + ' makes woof';
};

const rex = new Dog('Rex');
rex.speak();                 // 'Rex makes woof'
rex instanceof Dog;          // true
rex instanceof Animal;       // true

Three lines carry the load here. Animal.call(this, name) calls the parent constructor on your own this so that name gets set. Dog.prototype = Object.create(Animal.prototype) hooks in the prototype chain, so that a Dog instance searches first at Dog.prototype, then at Animal.prototype, then at Object.prototype. And the third line repairs something the second one broke: overwriting Dog.prototype lost the constructor back-reference, which we restore manually. Details like these are exactly what you forget in practice – and what class takes off your hands.

The same thing as a class#

Now the same code in ES2015 syntax, imagined side by side. The result is identical in the object model – the same prototype objects, the same chain, the same shared methods:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return this.name + ' makes a sound';
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name);
  }
  speak() {
    return this.name + ' makes woof';
  }
}

const rex = new Dog('Rex');
Object.getPrototypeOf(rex) === Dog.prototype;              // true
Object.getPrototypeOf(Dog.prototype) === Animal.prototype; // true

Compare this with the ES5 version, and the translation becomes immediately visible. The speak methods in the class body end up on Animal.prototype and Dog.prototype – not on the instance. extends Animal takes care of hooking in the chain, for which we just wrote Object.create(Animal.prototype) by hand. And super(name) replaces the manual Animal.call(this, name). The last line proves it: rex points to Dog.prototype, and that points to Animal.prototype. The same chain as before, just without the boilerplate and without the forgotten constructor line.

You still have to be honest, though: class is syntactic sugar, but not exclusively. A class body always runs in strict mode. A class can’t be called without new – the attempt throws an error, whereas a constructor function could also be misused as a regular function. And class declarations aren’t hoisted to the top and initialized like function declarations; they sit in a temporal dead zone and can’t be used before the line where they are defined. super in methods also relies on an internal mechanism ([[HomeObject]]) that you can’t replicate one to one in plain ES5. So the facade is convenient and, at a few edges, stricter than the original – but the model underneath is still prototypes.

Cleanly separating prototype, __proto__, and Object.create#

The most common confusion I run into in code reviews revolves around two similar-sounding names. prototype and __proto__ are not the same, and mixing them up produces bugs you stare at for a long time. This list sorts out the three tools:

  • A constructible function usually has its own prototype property. new uses the object referenced there as the prototype of the instance. Ordinary instances don’t have their own prototype property; arrow functions and methods aren’t constructible and don’t have such a template either.
  • __proto__ (or the internal [[Prototype]]) is the actual chain link that every object carries. The canonical access goes through Object.getPrototypeOf(obj); __proto__ itself is only standardized in ES2015 via Annex B and is considered legacy.
  • Object.create(proto) creates an object and sets its [[Prototype]] directly to proto – with no constructor function at all. That is the direct way to lay down a chain link.

The crucial difference: Fn.prototype is the template on the function, instance.[[Prototype]] is the link on the created object. When new Fn() is called, one becomes the other. And to untangle it once and for all – the function itself is also an object and has its own link:

function Fn() {}
const obj = new Fn();

Object.getPrototypeOf(obj) === Fn.prototype; // true  (Instanz-Link)
obj.prototype;                               // undefined (Instanz hat keine)
Object.getPrototypeOf(Fn) === Function.prototype; // true (Fn ist selbst Objekt)

Pay attention to the last line. Fn.__proto__ is Function.prototype, not Fn.prototype. If you mix these two up, you look for methods in the wrong place. When in doubt, Object.getPrototypeOf always helps you walk the chain step by step instead of guessing.

The most expensive pitfall: methods in the constructor#

Now to the point that costs memory in real codebases and often slips through reviews. It makes a tangible difference whether a method lives on the prototype or is created in the constructor:

function WidgetBad() {
  this.render = function () { /* ... */ }; // pro Instanz eine neue Funktion
}

function WidgetGood() {}
WidgetGood.prototype.render = function () { /* ... */ }; // geteilt

const a1 = new WidgetBad();
const a2 = new WidgetBad();
a1.render === a2.render; // false  -> zwei getrennte Funktionen

const b1 = new WidgetGood();
const b2 = new WidgetGood();
b1.render === b2.render; // true   -> eine Funktion, geteilt

The proof is in the comparisons. With WidgetBad, every instance gets its own render function – with a thousand widgets, that is a thousand identical functions in memory. With WidgetGood, render lives once on WidgetGood.prototype, and all instances share it. That is exactly what class does automatically: methods in the class body end up on the prototype, not on the instance. So with class, you don’t have to make any effort for the good case – you just must not destroy it with an assignment in the constructor.

The second common pitfall is losing this. A prototype method only knows its receiver when it is called as obj.method(). If you detach it, the binding is gone:

const cat = new Animal('Minka');

const fn = cat.speak;
fn(); // this ist nicht mehr cat -> Fehler oder falsches Ergebnis

const bound = cat.speak.bind(cat);
bound(); // 'Minka makes a sound' -> this wieder gebunden

That is not a bug but a direct consequence of the model: this is determined at call time, not at definition time. If you pull cat.speak out into a free variable, the receiver is missing. The tools against this are established in 2017: .bind(cat) creates a permanently bound variant, or you wrap the call in an arrow function that takes this from the surrounding scope. A side note on what is coming: class fields with arrow functions are in the works and are meant to make exactly this binding more elegant – but at the end of 2017, that is still a TC39 proposal and not a standard. If you need it in production today, reach for bind or an arrow wrapper.

Why this pays off#

You can write JavaScript with class for years without ever saying “prototype.” Until the day this is undefined in an event handler, an inherited method can’t be found, or a profiler shows the same function a thousand times in the heap. That is when the people who know the model part ways with the people who guess. The three recurring symptoms – lost this, a method in the wrong place, memory per instance – are not quirks of the language but logical consequences of a chain of objects pointing to each other.

class has its place: readable, strict, and it takes the error-prone boilerplate of ES5 inheritance off your hands. But it is a facade, and behind the facade there is still Object.create, Fn.prototype, and a new that connects the two. The next time you write extends, think briefly about the three lines it replaces – the hooked-in chain, the super call, the constructor back-reference. Then class is no longer magic but a shortcut whose long form you could write out yourself at any time.

This prototypal thinking is the same common thread that runs through the JavaScript patterns that stayed – objects pointing to objects, functions as building blocks. If you understand this foundation, you build on frameworks more calmly.

Further reading#

Revised and translated from German with the help of AI.