Why do you need to reset javascript constructor du

2020-06-24 06:05发布

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;

1条回答
趁早两清
2楼-- · 2020-06-24 07:05

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.

查看更多
登录 后发表回答