为什么将构造函数从 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;
最佳答案
从技术上讲,您不需要这样做,但是由于您要替换整个 .prototype
对象,您将丢失 .constructor
默认情况下放在那里,因此如果您有依赖它的代码,则需要手动包含它。
关于javascript - 为什么在继承过程中需要重置 javascript 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222696/