liveBook · Manning

Constructor property

As explained in Secrets of the JavaScript Ninja, Second Edition

A property that references a constructor function associated with an object or prototype.

A function’s prototype object has a constructor property pointing back to that function. Instances can access this reference through the prototype chain, use it to check an apparent origin, or call it to create another instance. section 7.2.3 section 7.5

Listing 7.5. Examining the type of an instance and its constructor
function Ninja(){}
const ninja = new Ninja();

assert(typeof ninja === "object",                                  #A
      "The type of the instance is object.");
assert(ninja instanceof Ninja,                                     #B
       "instanceof identifies the constructor." );
assert(ninja.constructor === Ninja,                                #C
       "The ninja object was created by the Ninja function.");

Compare typeof, instanceof, and constructor to see how each check describes a Ninja instance. section 7.2.3

Watch for a broken back-reference when replacing a constructor’s prototype:

  • If Ninja.prototype is replaced with a Person instance, lookup can reach Person’s constructor property, so ninja.constructor identifies Person instead of Ninja. section 7.3.1
  • Restore the link with Object.defineProperty, setting constructor to Ninja and making the property non-enumerable. section 7.3.1

Construct another instance

After creating ninja with new Ninja(), new ninja.constructor() creates a distinct Ninja instance, even when the original constructor is no longer in scope. section 7.2.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Shows prototype-chain lookup and repair after prototype replacement, including the descriptor setting needed to restore the reference.
Examples
Demonstrates Ninja instance checks and construction, then shows Person inheritance breaking Ninja’s constructor reference.
What you can do after
Apply constructor references to check an instance’s apparent origin, create another instance, and restore a reference after prototype replacement.
How it connects
Connects constructor properties to constructor functions, prototypes, instanceof, inheritance, and property descriptors.

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.