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?

function Animal(gender) {
    this.gender = gender;
}

Animal.prototype.sayAnimal = function() {
    return "I am an animal"
}

function Dog(gender, barkSound) {
    Animal.call(this, gender)
    this.barkSound = barkSound
}

Dog.prototype = Object.create(Animal.prototype) 

Dog.prototype.constructor = Dog 

Advertisement

Answer

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

class ExtendedArray extends Array {
}

const e = new ExtendedArray();
console.log(e.constructor === ExtendedArray);

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:

function Animal(gender) {
}
function Dog(gender, barkSound) {
    Animal.call(this, gender)
}
Dog.prototype = Object.create(Animal.prototype)

// oops, this refers to Animal...
console.log(Dog.prototype.constructor);

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

Advertisement