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