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
x
17
17
1
function Animal(gender) {
2
this.gender = gender;
3
}
4
5
Animal.prototype.sayAnimal = function() {
6
return "I am an animal"
7
}
8
9
function Dog(gender, barkSound) {
10
Animal.call(this, gender)
11
this.barkSound = barkSound
12
}
13
14
Dog.prototype = Object.create(Animal.prototype)
15
16
Dog.prototype.constructor = Dog
17
Advertisement
Answer
Users of classes will expect the .constructor
property of instances to refer to the constructor of that instance. For example:
JavaScript
1
5
1
class ExtendedArray extends Array {
2
}
3
4
const e = new ExtendedArray();
5
console.log(e.constructor === ExtendedArray);
If you’re using function
s 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
1
9
1
function Animal(gender) {
2
}
3
function Dog(gender, barkSound) {
4
Animal.call(this, gender)
5
}
6
Dog.prototype = Object.create(Animal.prototype)
7
8
// oops, this refers to Animal...
9
console.log(Dog.prototype.constructor);
That said, it probably isn’t an issue in most situations.