16

In JavaScript Prototype inheritance, what is the goal of adding prototype.constructor property. Let me explain with an example.

var Super = function() {
    this.superProperty = 'Super Property'
}
var Sub = function() {
    this.subProperty = 'Sub Property'
}

Sub.prototype = new Super();
Sub.prototype.constructor = Sub; // advantages of the statement

var inst = new Sub();

The following lines return always true in all case, when adding Sub.prototype.constructor = Sub or not.

console.log(inst instanceof Sub)   // true
console.log(inst instanceof Super) // true

I guess, it may be useful when getting new instances but when and/or how?

Thanks in advance.

Fatih Acet
  • 28,690
  • 9
  • 51
  • 58
  • See also [Why is it necessary to set the prototype constructor?](https://stackoverflow.com/q/8453887/1048572) – Bergi Jun 16 '22 at 23:50

1 Answers1

10

It's just to properly reset the constructor property to accurately reflect the function used to construct the object.

Sub.prototype = new Super();

console.log(new Sub().constructor == Sub);
// -> 'false' 

Sub.prototype.constructor = Sub;
console.log(new Sub().constructor == Sub);
// -> 'true' 
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 2
    What exactly is the consequence of not setting it? Or in other words, when does the value of Sub.prototype.constructor ever actually matter? It does not seem to affect the creation of instances of Sub at all, afaics. This must be one of those things that are "so obvious" that nobody actually states it outright, and thus it has eluded me :-) – Yetanotherjosh Jul 30 '13 at 06:36
  • 6
    @Yetanotherjosh: well, in the case of the OP's code, if he leaves that line out, then `inst.constructor === Super`, even though it was instantiated with `new Sub()`. This generally wouldn't be a problem if you don't care about that property, but if you were sharing the instance with other code then you might cause confusion in some cases, including where `new inst.constructor()` would actually result in an instance of `Super()` and not `Sub()` (so it would be missing properties exclusive to `Sub.prototype`). **tl;dr it's a good programming practice**. – Andy E Jul 30 '13 at 12:08