为什么在继承期间需要重置javascript构造函数?

use*_*123 3 javascript constructor

为什么将构造函数从Mammal重置为Cat很重要?我一直在玩这个代码,并没有发现任何"错误"构造函数的负面影响.

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;
}
Run Code Online (Sandbox Code Playgroud)

例如:

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;
Run Code Online (Sandbox Code Playgroud)

I H*_*azy 7

从技术上讲,你不需要这样做,但是因为你要替换整个.prototype对象.constructor,所以默认情况下你丢失了它,所以如果你有依赖它的代码,你需要手动包含它.