What’s up with the 'constructor' property in JavaScript?
Join the DZone community and get the full member experience.
Join For FreeAll 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 trueThe 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 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.
obj instanceof Cis 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?
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 trueThus, 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:
- Relevant sections in the ECMAScript 5 language specification:
13.2. Creating Function Objects
15.2.4.1. Object.prototype.constructor
- An easy way to understand JavaScript’s prototypal inheritance
- JavaScript values: not everything is an object
From http://www.2ality.com/2011/06/constructor-property.html
Property (programming)
JavaScript
Opinions expressed by DZone contributors are their own.
Comments