Skip to content

Why does Dog.prototype.constructor === Dog ?

2013 June 26
by Richard Harrington

Question: In JavaScript, why does a constructor’s prototype’s constructor equal the constructor itself? In other words, why does

Dog.prototype.constructor === Dog


Short Answer: So that this will work:

var Dog = function(){}
var myDog = new Dog();
myDog.constructor === Dog;
=> true

Long Answer:

What confused me when I first started learning this stuff was the use of the word “prototype” as a property name. It seems like the “prototype” property of an object should refer to that object’s prototype, but it doesn’t.* A constructor’s “prototype” property is not a pointer to the object that the constructor looks to when it wants to start looking up its own prototype chain; rather, it is a pointer to the object that the objects created by that constructor look to when they want to start looking up their prototype chains.

Therefore, when one of those objects wants to see which object created it, it accesses its “constructor” property. Since it has no “constructor” property of its own, it starts up its prototype chain to find a “constructor” property. The first place it looks is the “prototype” property of its constructor function, which contains a property called “constructor,” and that “constructor” property should point to the constructor of the object that started the prototype chain lookup.

In order for that to work, every constructor has to have a “prototype” property which has a “constructor” property which points back to itself, the constructor, so that objects created by that constructor will be pointed to it when they start looking up their prototype chains. So that’s why MyObject.prototype.constructor == MyObject.

Keep in mind also that this “constructor” property is totally unsafe and not to be trusted, unless you take care to keep it intact. At the time any function is defined, it gets a “prototype” property which points to an object having exactly one property: “constructor.” After that, it’s fair game. You can reassign the “constructor” property to anything you want, or, more commonly, you can reassign the entire “prototype” property itself, which will eliminate the “constructor” property. This can sometimes be convenient, but if you care about preserving the “constructor” property (and you may not), then you have to reset it manually after reassigning the “prototype” property. For instance:

var Seal = function(){}
Seal.prototype = {
    waveFlippers: function() { ... },
    bark: function() { ... },
    chillOutOnTheSand: function() { ... }
Seal.prototype.constructor = Seal;

* For that, you used to have only the special property __proto__ which was non-standard and only worked in certain browsers, and now in ECMAScript 5 you have Object.getPrototypeOf(object)

Leave a Reply

Note: You may use basic HTML in your comments. Your email address will not be published.

Subscribe to this comment feed via RSS