Skip to content
Advertisement

JS: Why do you need to reset the constructor back after inheriting another prototype?

In the example below, why is Dog.prototype.constructor = Dog needed? I under we use: Dog.prototype = Object.create(Animal.prototype) to inherit the sayAnimal() and any other functions added to the Animal prototype but how does that effect the constructor? What would leaving it out do?

JavaScript

Advertisement

Answer

Users of classes will expect the .constructor property of instances to refer to the constructor of that instance. For example:

JavaScript

If you’re using functions and extending manually, then if you don’t set the constructor property on the subclass prototype explicitly, the .constructor will refer not to the subclass constructor (as a user of the code would usually expect), but to the superclass:

JavaScript

That said, it probably isn’t an issue in most situations.

Advertisement