liveBook · Manning

Instanceof operator

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript operator that tests whether an object was created by, or inherits from, a particular constructor via its prototype chain.

Need to know whether an object belongs to a constructor’s inheritance chain? `typeof` only reports `"object"` for a constructed instance. `instanceof` gives a more useful test: `object instanceof Constructor`. section 7.2.3

The test is about prototypes, not a permanent record of who created the object. JavaScript checks whether the constructor’s current `prototype` object appears anywhere in the object’s prototype chain. A match returns `true`, whether the prototype is the object’s direct prototype or farther up the chain. section 7.3.2

Inheritance, not imitation

Suppose `Ninja.prototype = new Person()` before `const ninja = new Ninja()`. Both `ninja instanceof Ninja` and `ninja instanceof Person` are true. Merely copying a method from `Person.prototype` onto `Ninja.prototype` would give the object that method, but would not make `ninja instanceof Person` true. The chain matters; a matching method name does not. section 7.3 section 7.3.2

Watch for a moving target: replacing `Ninja.prototype` after creating `ninja` can make a previously true `ninja instanceof Ninja` test false. The operator compares against the constructor’s prototype *now*, while the existing object retains its earlier chain. section 7.3.2

Listing 7.12. Watch out for changes to constructor prototypes
function Ninja(){}

const ninja = new Ninja();

assert(ninja instanceof Ninja, "Our ninja is a Ninja!");

Ninja.prototype = {};                                                   #A

assert(!(ninja instanceof Ninja), "The ninja is now not a Ninja!?");    #B

Run the before-and-after assertions to see a prototype replacement reverse an `instanceof` result for the same object. section 7.3.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Works through prototype-chain matching and shows how replacing a constructor’s prototype reverses an existing object’s result.
Examples
Contrasts copied methods with inherited prototypes and tests an existing instance before and after prototype replacement.
What it assumes
Assumes familiarity with JavaScript functions and objects; establishes how construction connects an object to a function’s prototype.
What you can do after
Diagnose/debug with it: explain a surprising type-check result by inspecting the constructor’s current prototype and the object’s chain.
How it connects
Connects constructor functions, the `new` operator, prototype chains, inheritance, `typeof`, and the `constructor` property.

Also explained in

Compare how 2 books explain instanceof operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.