What’s up with the 'constructor' property in JavaScript?

DZone 's Guide to

What’s up with the 'constructor' property in JavaScript?

· Web Dev Zone ·
Free Resource

All objects produced by built-in constructor functions in JavaScript have a property called constructor. This post explains what that property is all about.

The constructor property

If you examine the property, in turns out that it points back to – surprise – the constructor of an object.
    > new String("abc").constructor === String
The constructor property serves two purposes:
  • Get the class of an object: Remember that constructor functions can be considered classes in JavaScript. Thus, getting the constructor of an object gives you its class. For example, the following two instances of String have the same class:
        > var a = new String("abc");
        > var b = new String("def");
        > a.constructor === b.constructor
  • Create a new instance: Given an object, you can create a new instance that has the same class.
        > var str1 = new String("abc");
        > var str2 = new str1.constructor("xyz");
        > str2 instanceof String
    This is mainly useful if you have several subclasses and want to clone an instance.
Note that the instanceof operator does not use the constructor property. The result of the expression
    obj instanceof C
is determined by whether C.prototype is in the prototype chain of obj. The expression is thus equivalent to

Where does the constructor property come from?

If you examine an instance of a constructor, you find out that it does not own the property, but inherits it from its prototype:
    > function Foo() {}
    > var f = new Foo();
    > Object.getOwnPropertyNames(f)
    > Object.getOwnPropertyNames(Object.getPrototypeOf(f))
    [ 'constructor' ]
JavaScript even sets up that property for you:
    > var f = function() {};
    > Object.getOwnPropertyNames(f.prototype)
    [ 'constructor' ]
    > f.prototype.constructor === f
Thus, you should avoid replacing the complete prototype value of a constructor with your own object and only add new properties to it. Alas, with subclassing, you have no choice and have to set the constructor property yourself.

Related reading:

  1. Relevant sections in the ECMAScript 5 language specification:
    13.2. Creating Function Objects Object.prototype.constructor
  2. An easy way to understand JavaScript’s prototypal inheritance
  3. JavaScript values: not everything is an object


From http://www.2ality.com/2011/06/constructor-property.html


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}