3

为什么将构造函数从 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;
}

例如:

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;
4

1 回答 1

7

从技术上讲,您不需要这样做,但是由于您要替换整个.prototype对象,因此您会丢失.constructor默认放置的对象,因此如果您有依赖它的代码,则需要手动包含它。

于 2012-11-04T20:44:24.280 回答