2011-06-22

What’s up with the “constructor” property in JavaScript?

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, you’ll find out that it points to – surprise – the constructor of an object.
    > new String("abc").constructor === String
    true
The constructor property serves three 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
        true
    
  • 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
        true
    
    This is mainly useful if you have several subclasses and want to clone an instance.
  • Invoking a super-constructor: You need the constructor property at (*), below.
        function Super(x) { ... }
        Super.prototype.foo = ...
        
        function Sub(x, y) {
            Sub.superclass.constructor.call(this, x); // (*)
        }
        Sub.superclass = Super.prototype;
        Sub.prototype = Object.create(Sub.superclass);
        Sub.prototype.constructor = Sub;
    
    Assigning the super-prototype to Sub.superclass avoids the hardcoded use of the superclass name in the sub-constructor. It can be used to similar effect in methods:
        Sub.prototype.foo = function (...) {
            Sub.superclass.foo.apply(this, arguments);
        };
    
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
    C.prototype.isPrototypeOf(obj)

Where does the constructor property come from?

It turns out that an instance does not own the constructor 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
    true
Best practice: 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
    15.2.4.1. Object.prototype.constructor
  2. An easy way to understand JavaScript’s prototypal inheritance
  3. JavaScript values: not everything is an object

No comments: