Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need to reset javascript constructor during inheritance?

Why is it important that I reset the constructor from Mammal to Cat? I've been playing around with this code and haven't found any negative effects of having the "wrong" constructor.

function Mammal(name){
    this.name=name;
    this.offspring=[];
}

Cat.prototype = new Mammal();        // Here's where the inheritance occurs
Cat.prototype.constructor=Cat;       // Otherwise instances of Cat would have a constructor of Mammal

function Cat(name){
    this.name=name;
}

for example:

function Mammal(name){
    this.name=name;
    this.offspring=[];
}

Cat.prototype = new Mammal();        // Here's where the inheritance occurs


function Cat(name){
    this.name=name;
    this.hasFur = true;
}

c1 = new Cat();
alert(c1.hasFur); //returns true;
like image 740
user1099123 Avatar asked Mar 06 '26 15:03

user1099123


1 Answers

Technically you don't need to do that, but since you're replacing the entire .prototype object, you're losing the .constructor that's put there by default, so if you have code that relies on it, you need to manually include it.

like image 50
I Hate Lazy Avatar answered Mar 09 '26 03:03

I Hate Lazy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!