Please support this book: buy it or donate

26. Prototype chains and classes



In this book, JavaScript’s style of object-oriented programming (OOP) is introduced in four steps. This chapter covers steps 2–4, the previous chapter covers step 1. The steps are (fig. 8):

  • Single objects: How do objects, JavaScript’s basic OOP building blocks, work in isolation?
  • Prototype chains: Each object has a chain of zero or more prototype objects. Prototypes are JavaScript’s core inheritance mechanism.
  • Classes: JavaScript’s classes are factories for objects. The relationship between a class and its instances is based on prototypal inheritance.
  • Subclassing: The relationship between a subclass and its superclass is also based on prototypal inheritance.
    Figure 8: This book introduces object-oriented programming in JavaScript in four steps.
    Figure 8: This book introduces object-oriented programming in JavaScript in four steps.

26.1. Prototype chains

Prototypes are JavaScript’s only inheritance mechanism: Each object has a prototype that is either null or an object. In the latter case, the object inherits all of the prototype’s properties.

In an object literal, you can set the prototype via the special property proto:

  1. const proto = {
  2. protoProp: 'a',
  3. };
  4. const obj = {
  5. __proto__: proto,
  6. objProp: 'b',
  7. };
  8. // obj inherits .protoProp:
  9. assert.equal(obj.protoProp, 'a');
  10. assert.equal('protoProp' in obj, true);

Given that a prototype object can have a prototype itself, we get a chain of objects – the so-called prototype chain. That means that inheritance gives us the impression that we are dealing with single objects, but we are actually dealing with chains of objects.

Fig. 9 shows what the prototype chain of obj looks like.

Figure 9: obj starts a chain of objects that continues with proto and other objects.

Figure 9: obj starts a chain of objects that continues with proto and other objects.

Non-inherited properties are called own properties. obj has one own property, .objProp.

26.1.1. Pitfall: only first member of prototype chain is mutated

One aspect of prototype chains that may be counter-intuitive is that setting any property via an object – even an inherited one – only changes that object – never one of the prototypes.

Consider the following object obj:

  1. const proto = {
  2. protoProp: 'a',
  3. };
  4. const obj = {
  5. __proto__: proto,
  6. objProp: 'b',
  7. };

When we set the inherited property obj.protoProp in line A, we “change” it by creating an own property: When reading obj.protoProp, the own property is found first and its value overrides the value of the inherited property.

  1. assert.deepEqual(Object.keys(obj), ['objProp']);
  2. obj.protoProp = 'x'; // (A)
  3. // We created a new own property:
  4. assert.deepEqual(Object.keys(obj), ['objProp', 'protoProp']);
  5. // The inherited property itself is unchanged:
  6. assert.equal(proto.protoProp, 'a');

The prototype chain of obj is depicted in fig. 10.

Figure 10: The own property .protoProp of obj overrides the property inherited from proto.

Figure 10: The own property .protoProp of obj overrides the property inherited from proto.

26.1.2. Tips for working with prototypes (advanced)

26.1.2.1. Avoid proto (except in object literals)

I recommend to avoid the special property proto: It is implemented via a getter and a setter in Object.prototype and therefore only available if Object.prototype is in the prototype chain of an object. That is usually the case, but to be safe, you can use these alternatives:

  • The best way to set a prototype is when creating an object. E.g. via:
  1. Object.create(proto: Object) : Object

If you have to, you can use Object.setPrototypeOf() to change the prototype of an existing object.

  • The best way to get a prototype is via the following method:
  1. Object.getPrototypeOf(obj: Object) : Object

This is how these features are used:

  1. const proto1 = {};
  2. const proto2 = {};
  3. const obj = Object.create(proto1);
  4. assert.equal(Object.getPrototypeOf(obj), proto1);
  5. Object.setPrototypeOf(obj, proto2);
  6. assert.equal(Object.getPrototypeOf(obj), proto2);

Note that proto in object literals is different. There, it is a built-in feature and always safe to use.

26.1.2.2. Check: is an object a prototype of another one?

A looser definition of “o is a prototype of p” is “o is in the prototype chain of p”. This relationship can be checked via:

  1. p.isPrototypeOf(o)

For example:

  1. const p = {};
  2. const o = {__proto__: p};
  3. assert.equal(p.isPrototypeOf(o), true);
  4. assert.equal(o.isPrototypeOf(p), false);
  5. // Object.prototype is almost always in the prototype chain
  6. // (more on that later)
  7. assert.equal(Object.prototype.isPrototypeOf(p), true);

26.1.3. Sharing data via prototypes

Consider the following code:

  1. const jane = {
  2. name: 'Jane',
  3. describe() {
  4. return 'Person named '+this.name;
  5. },
  6. };
  7. const tarzan = {
  8. name: 'Tarzan',
  9. describe() {
  10. return 'Person named '+this.name;
  11. },
  12. };
  13. assert.equal(jane.describe(), 'Person named Jane');
  14. assert.equal(tarzan.describe(), 'Person named Tarzan');

We have two objects that are very similar. Both have two properties whose names are .name and .describe. Additionally, method .describe() is the same. How can we avoid that method being duplicated?

We can move it to a shared prototype, PersonProto:

  1. const PersonProto = {
  2. describe() {
  3. return 'Person named ' + this.name;
  4. },
  5. };
  6. const jane = {
  7. __proto__: PersonProto,
  8. name: 'Jane',
  9. };
  10. const tarzan = {
  11. __proto__: PersonProto,
  12. name: 'Tarzan',
  13. };

The name of the prototype reflects that both jane and tarzan are persons.

Figure 11: Objects jane and tarzan share method .describe(), via their common prototype PersonProto.

Figure 11: Objects jane and tarzan share method .describe(), via their common prototype PersonProto.

The diagram in fig. 11 illustrates how the three objects are connected: The objects at the bottom now contain the properties that are specific to jane and tarzan. The object at the top contains the properties that is shared between them.

When you make the method call jane.describe(), this points to the receiver of that method call, jane (in the bottom left corner of the diagram). That’s why the method still works. The analogous thing happens when you call tarzan.describe().

  1. assert.equal(jane.describe(), 'Person named Jane');
  2. assert.equal(tarzan.describe(), 'Person named Tarzan');

26.2. Classes

We are now ready to take on classes, which are basically a compact syntax for setting up prototype chains. While their foundations may be unconventional, working with JavaScript’s classes should still feel familiar – if you have used an object-oriented language before.

26.2.1. A class for persons

We have previously worked with jane and tarzan, single objects representing persons. Let’s use a class to implement a factory for persons:

  1. class Person {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. describe() {
  6. return 'Person named '+this.name;
  7. }
  8. }

jane and tarzan can now be created via new Person():

  1. const jane = new Person('Jane');
  2. assert.equal(jane.describe(), 'Person named Jane');
  3. const tarzan = new Person('Tarzan');
  4. assert.equal(tarzan.describe(), 'Person named Tarzan');

26.2.2. Class expressions

The previous class definition was a class declaration. There are also anonymous class expressions:

  1. const Person = class { ··· };

And named class expressions:

  1. const Person = class MyClass { ··· };

26.2.3. Classes under the hood (advanced)

There is a lot going on under the hood of classes. Let’s look at the diagram for jane (fig. 12).

Figure 12: The class Person has the property .prototype that points to an object that is the prototype of all instances of Person. jane is one such instance.

Figure 12: The class Person has the property .prototype that points to an object that is the prototype of all instances of Person. jane is one such instance.

The main purpose of class Person is to set up the prototype chain on the right (jane, followed by Person.prototype). It is interesting to note that both constructs inside class Person (.constructor and .describe()) created properties for Person.prototype, not for Person.

The reason for this slightly odd approach is backward compatibility: Prior to classes, constructor functions (ordinary functions, invoked via the new operator) were often used as factories for objects. Classes are mostly better syntax for constructor functions and therefore remain compatible with old code. That explains why classes are functions:

  1. > typeof Person
  2. 'function'

In this book, I use the terms constructor (function) and class interchangeably.

Many people confuse .proto and .prototype. Hopefully, the diagram in fig. 12 makes it clear, how they differ:

  • .proto is a special property for accessing the prototype of an object.
  • .prototype is a normal property that is only special due to how the new operator uses it. The name is not ideal: Person.prototype does not point to the prototype of Person, it points to the prototype of all instances of Person.
26.2.3.1. Person.prototype.constructor

There is one detail in fig. 12 that we haven’t looked at, yet: Person.prototype.constructor points back to Person:

  1. > Person.prototype.constructor === Person
  2. true

This setup is also there for historical reasons. But it also has two benefits.

First, each instance of a class inherits property .constructor. Therefore, given an instance, you can make “similar” objects via it:

  1. const jane = new Person('Jane');
  2. const cheeta = new jane.constructor('Cheeta');
  3. // cheeta is also an instance of Person
  4. // (the instanceof operator is explained later)
  5. assert.equal(cheeta instanceof Person, true);

Second, you can get the name of the class that created a given instance:

  1. const tarzan = new Person('Tarzan');
  2. assert.equal(tarzan.constructor.name, 'Person');

26.2.4. Class definitions: prototype properties

The following code demonstrates all parts of a class definition Foo that create properties of Foo.prototype:

  1. class Foo {
  2. constructor(prop) {
  3. this.prop = prop;
  4. }
  5. protoMethod() {
  6. return 'protoMethod';
  7. }
  8. get protoGetter() {
  9. return 'protoGetter';
  10. }
  11. }

Let’s examine them in order:

  • .constructor() is called after creating a new instance of Foo, to set up that instance.
  • .protoMethod() is a normal method. It is stored in Foo.prototype.
  • .protoGetter is a getter that is stored in Foo.prototype.
    The following interaction uses class Foo:
  1. > const foo = new Foo(123);
  2. > foo.prop
  3. 123
  4. > foo.protoMethod()
  5. 'protoMethod'
  6. > foo.protoGetter
  7. 'protoGetter'

26.2.5. Class definitions: static properties

The following code demonstrates all parts of a class definition that create so-called static properties – properties of the class itself.

  1. class Bar {
  2. static staticMethod() {
  3. return 'staticMethod';
  4. }
  5. static get staticGetter() {
  6. return 'staticGetter';
  7. }
  8. }

The static method and the static getter are used as follows.

  1. > Bar.staticMethod()
  2. 'staticMethod'
  3. > Bar.staticGetter
  4. 'staticGetter'

26.2.6. The instanceof operator

The instanceof operator tells you if a value is an instance of a given class:

  1. > new Person('Jane') instanceof Person
  2. true
  3. > ({}) instanceof Person
  4. false
  5. > ({}) instanceof Object
  6. true
  7. > [] instanceof Array
  8. true

We’ll explore the instanceof operator in more detail later, after we have looked at subclassing.

26.2.7. Why I recommend classes

I recommend using classes for the following reasons:

  • Classes are a common standard for object creation and inheritance that is now widely supported across frameworks (React, Angular, Ember, etc.).
  • They help tools such as IDEs and type checkers with their work and enable new features.
  • They are a foundation for future features such as value objects, immutable objects, decorators, etc.
  • They make it easier for newcomers to get started with JavaScript.
  • JavaScript engines optimize them. That is, code that uses classes is usually faster than code that uses a custom inheritance library.
    That doesn’t mean that classes are perfect. One issue I have with them, is:

  • Classes look different from what they are under the hood. In other words, there is a disconnect between syntax and semantics.
    It would be nice if classes were (syntax for) constructor objects (new-able prototype objects) and not to constructor functions. But backward compatibility is a legitimate reason for them being the latter.

26.3. Private data for classes

This section describes techniques for hiding some of the data of an object from the outside. We discuss them in the context of classes, but they also work for objects created directly, via object literals etc.

26.3.1. Private data: naming convention

The first technique makes a property private by prefixing its name with an underscore. This doesn’t protect the property in any way; it merely signals to the outside: “You don’t need to know about this property.”

In the following code, the properties ._counter and ._action are private.

  1. class Countdown {
  2. constructor(counter, action) {
  3. this._counter = counter;
  4. this._action = action;
  5. }
  6. dec() {
  7. if (this._counter < 1) return;
  8. this._counter--;
  9. if (this._counter === 0) {
  10. this._action();
  11. }
  12. }
  13. }
  14. // The two properties aren’t really private:
  15. assert.deepEqual(
  16. Reflect.ownKeys(new Countdown()),
  17. ['_counter', '_action']);

With this technique, you don’t get any protection and private names can clash. On the plus side, it is easy to use.

26.3.2. Private data: WeakMaps

Another technique is to use WeakMaps. How exactly that works is explained in the chapter on WeakMaps. This is a preview:

  1. let _counter = new WeakMap();
  2. let _action = new WeakMap();
  3. class Countdown {
  4. constructor(counter, action) {
  5. _counter.set(this, counter);
  6. _action.set(this, action);
  7. }
  8. dec() {
  9. let counter = _counter.get(this);
  10. if (counter < 1) return;
  11. counter--;
  12. _counter.set(this, counter);
  13. if (counter === 0) {
  14. _action.get(this)();
  15. }
  16. }
  17. }
  18. // The two pseudo-properties are truly private:
  19. assert.deepEqual(
  20. Reflect.ownKeys(new Countdown()),
  21. []);

This technique offers you considerable protection from outside access and there can’t be any name clashes. But it is also more complicated to use.

26.3.3. More techniques for private data

There are more techniques for private data for classes. These are explained in “Exploring ES6”.

The reason why this section does not go into much depth, is that JavaScript will probably soon have built-in support for private data. Consult the ECMAScript proposal “Class Public Instance Fields & Private Instance Fields” for details.

26.4. Subclassing

Classes can also subclass (“extend”) existing classes. As an example, the following class Employee subclasses Person:

  1. class Person {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. describe() {
  6. return `Person named ${this.name}`;
  7. }
  8. static logNames(persons) {
  9. for (const person of persons) {
  10. console.log(person.name);
  11. }
  12. }
  13. }
  14. class Employee extends Person {
  15. constructor(name, title) {
  16. super(name);
  17. this.title = title;
  18. }
  19. describe() {
  20. return super.describe() +
  21. ` (${this.title})`;
  22. }
  23. }
  24. const jane = new Employee('Jane', 'CTO');
  25. assert.equal(
  26. jane.describe(),
  27. 'Person named Jane (CTO)');

Two comments:

  • Inside a .constructor() method, you must call the super-constructor via super(), before you can access this. That’s because this doesn’t exist before the super-constructor was called (this phenomenon is specific to classes).

  • Static methods are also inherited. For example, Employee inherits the static method .logNames():

  1. > 'logNames' in Employee
  2. true

26.4.1. Subclasses under the hood (advanced)

Figure 13: These are the objects that make up class Person and its subclass, Employee. The left column is about classes. The right column is about the Employee instance jane and its prototype chain.

Figure 13: These are the objects that make up class Person and its subclass, Employee. The left column is about classes. The right column is about the Employee instance jane and its prototype chain.

The classes Person and Employee from the previous section are made up of several objects (fig. 13). One key insight for understanding how these objects are related, is that there are two prototype chains:

  • The instance prototype chain, on the right.
  • The class prototype chain, on the left.
26.4.1.1. The instance prototype chain (right column)

The instance prototype chain starts with jane and continues with Employee.prototype and Person.prototype. In principle, the prototype chain ends at this point, but we get one more object: Object.prototype. This prototype provides services to virtually all objects, which is why it is included here, too:

  1. > Object.getPrototypeOf(Person.prototype) === Object.prototype
  2. true
26.4.1.2. The class prototype chain (left column)

In the class prototype chain, Employee comes first, Person next. Afterwards, the chain continues with Function.prototype, which is only there, because Person is a function and functions need the services of Function.prototype.

  1. > Object.getPrototypeOf(Person) === Function.prototype
  2. true

26.4.2. instanceof in more detail (advanced)

We have not yet seen how instanceof really works. Given the expression x instanceof C, how does instanceof determine if x is an instance of C? It does so by checking if C.prototype is in the prototype chain of x. That is, the following two expressions are equivalent:

  1. x instanceof C
  2. C.prototype.isPrototypeOf(x)

If we go back to fig. 13, we can confirm that the prototype chain does lead us to the following answers:

  1. > jane instanceof Employee
  2. true
  3. > jane instanceof Person
  4. true
  5. > jane instanceof Object
  6. true

26.4.3. Prototype chains of built-in objects (advanced)

Next, we’ll use our knowledge of subclassing to understand the prototype chains of a few built-in objects. The following tool function p() helps us with our explorations.

  1. const p = Object.getPrototypeOf.bind(Object);

We extracted method .getPrototypeOf() of Object and assigned it to p.

26.4.3.1. The prototype chain of {}

Let’s start by examining plain objects:

  1. > p({}) === Object.prototype
  2. true
  3. > p(p({})) === null
  4. true

Figure 14: The prototype chain of an object created via an object literal starts with that object, continues with Object.prototype and ends with null.

Figure 14: The prototype chain of an object created via an object literal starts with that object, continues with Object.prototype and ends with null.

Fig. 14 shows a diagram for this prototype chain. We can see that {} really is an instance of ObjectObject.prototype is in its prototype chain.

Object.prototype is a curious value: It is an object, but it is not an instance of Object:

  1. > typeof Object.prototype
  2. 'object'
  3. > Object.prototype instanceof Object
  4. false

That can’t be avoided, because Object.prototype can’t be in its own prototype chain.

26.4.3.2. The prototype chain of []

What does the prototype chain of an Array look like?

  1. > p([]) === Array.prototype
  2. true
  3. > p(p([])) === Object.prototype
  4. true
  5. > p(p(p([]))) === null
  6. true

Figure 15: The prototype chain of an Array has these members: the Array instance, Array.prototype, Object.prototype, null.

Figure 15: The prototype chain of an Array has these members: the Array instance, Array.prototype, Object.prototype, null.

This prototype chain (visualized in fig. 15) tells us that an Array object is an instance of Array, which is a subclass of Object.

26.4.3.3. The prototype chain of function () {}

Lastly, the prototype chain of an ordinary function tells us that all functions are objects:

  1. > p(function () {}) === Function.prototype
  2. true
  3. > p(p(function () {})) === Object.prototype
  4. true
26.4.3.4. Objects that aren’t instances of Object

An object is only an instance of Object if Object.prototype is in its prototype chain. Most objects created via various literals are instances of Object:

  1. > ({}) instanceof Object
  2. true
  3. > (() => {}) instanceof Object
  4. true
  5. > /abc/ug instanceof Object
  6. true

Objects that don’t have prototypes are not instances of Object:

  1. > ({ __proto__: null }) instanceof Object
  2. false
  3. > Object.create(null) instanceof Object
  4. false

Object.prototype ends most prototype chains. Its prototype is null, which means it isn’t an instance of Object, either:

  1. > Object.prototype instanceof Object
  2. false

26.4.4. Dispatched vs. direct method calls (advanced)

Let’s examine how method calls work with classes. We revisit jane from earlier:

  1. class Person {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. describe() {
  6. return 'Person named '+this.name;
  7. }
  8. }
  9. const jane = new Person('Jane');

Fig. 16 has a diagram with jane’s prototype chain.

Figure 16: The prototype chain of jane starts with jane and continues with Person.prototype.

Figure 16: The prototype chain of jane starts with jane and continues with Person.prototype.

Normal method calls are dispatched. To make the method call jane.describe():

  • JavaScript first looks for the value of jane.describe, by traversing the prototype chain.
  • Then it calls the function it found, while setting this to jane. this is the receiver of the method call (where the search for property .describe started).
    This way of dynamically looking for methods, is called dynamic dispatch.

You can make the same method call while bypassing dispatch:

  1. Person.prototype.describe.call(jane)

This time, Person.prototype.describe is an own property and there is no need to search the prototypes. We also specify this ourselves, via .call().

Note how this always points to the beginning of a prototype chain. That enables .describe() to access .name. And it is where the mutations happen (should a method want to set the .name).

26.4.4.1. Borrowing methods

Direct method calls become useful when you are working with methods of Object.prototype. For example, Object.prototype.hasOwnProperty() checks if an object has a non-inherited property whose key is as given:

  1. > const obj = { foo: 123 };
  2. > obj.hasOwnProperty('foo')
  3. true
  4. > obj.hasOwnProperty('bar')
  5. false

However, this method may be overridden. Then a dispatched method call doesn’t work:

  1. > const obj = { hasOwnProperty: true };
  2. > obj.hasOwnProperty('bar')
  3. TypeError: obj.hasOwnProperty is not a function

The work-around is to use a direct method call:

  1. > Object.prototype.hasOwnProperty.call(obj, 'bar')
  2. false
  3. > Object.prototype.hasOwnProperty.call(obj, 'hasOwnProperty')
  4. true

This kind of direct method call is often abbreviated as follows:

  1. > ({}).hasOwnProperty.call(obj, 'bar')
  2. false
  3. > ({}).hasOwnProperty.call(obj, 'hasOwnProperty')
  4. true

JavaScript engines optimize this pattern, so that performance should not be an issue.

26.4.5. Mixin classes (advanced)

JavaScript’s class system only supports single inheritance. That is, each class can have at most one superclass. A way around this limitation is via a technique called mixin classes (short: mixins).

The idea is as follows: Let’s assume there is a class C that extends a class S – its superclass. Mixins are class fragments that are inserted between C and S.

In JavaScript, you can implement a mixin Mix via a function whose input is a class and whose output is the mixin class fragment – a new class that extends the input. To use Mix(), you create C as follows.

  1. class C extends Mix(S) {
  2. ···
  3. }

Let’s look at an example:

  1. const Branded = S => class extends S {
  2. setBrand(brand) {
  3. this._brand = brand;
  4. return this;
  5. }
  6. getBrand() {
  7. return this._brand;
  8. }
  9. };

We use this mixin to insert a class between Car and Object:

  1. class Car extends Branded(Object) {
  2. constructor(model) {
  3. super();
  4. this._model = model;
  5. }
  6. toString() {
  7. return `${this.getBrand()} ${this._model}`;
  8. }
  9. }

The following code confirms that the mixin worked: Car has method .setBrand() of Branded.

  1. const modelT = new Car('Model T').setBrand('Ford');
  2. assert.equal(modelT.toString(), 'Ford Model T');

Mixins are more flexible than normal classes:

  • First, you can use the same mixin multiple times, in multiple classes.

  • Second, you can use multiple mixins at the same time. As an example, consider an additional mixin called Stringifiable that helps with implementing .toString(). We could use both Branded and Stringifiable as follows:

  1. class Car extends Stringifiable(Branded(Object)) {
  2. ···
  3. }