为什么在继承过程中需要重置javascript构造函数?

为什么在继承过程中需要重置javascript构造函数?,javascript,constructor,Javascript,Constructor,为什么将构造函数从哺乳动物重置为猫很重要?我一直在使用这段代码,没有发现使用“错误”构造函数的任何负面影响 function Mammal(name){ this.name=name; this.offspring=[]; } Cat.prototype = new Mammal(); // Here's where the inheritance occurs Cat.prototype.constructor=Cat; // Otherwise i

为什么将构造函数从哺乳动物重置为猫很重要?我一直在使用这段代码,没有发现使用“错误”构造函数的任何负面影响

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;
}
例如:

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;
从技术上讲,您不需要这样做,但是由于您正在替换整个
.prototype
对象,因此您将丢失默认放置在那里的
.constructor
,因此如果您有依赖它的代码,您需要手动包含它