The constructor
property is just a simple property of the prototype object. There is nothing magically happening with it behind the scenes. It's a property that can be overridden and reset, but it doesn't affect anything else.
So when you do this:
cat.prototype = Object.create(animal.prototype);
you are overriding the entire prototype property of the function cat
with a complete new object derived from the prototype
object of animal
. But since the constructor
property is just a normal property of the prototype
object, it will get overridden as well.
And yes, when implementing inheritance, the line
Class.prototype.constructor = Class;
is commonly added to restore the constructor
property to its original value and to kind of undo the "damage" that was done by this inheritance pattern.
So in your case, you would need to add the following line:
cat.prototype = Object.create(animal.prototype);
cat.prototype.constructor = cat; // <---- add this
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…