function Mammal(name){
   this.name = name;
}
Mammal.prototype.displayName = function(){
   return this.name;
}

function Organism(name){
   this.orgName = name;
}
Organism.prototype.print = function(){
    return this.orgName;
}

Organism.prototype = new Mammal();  //Organism inherits Mammal

//Testing
var o = new Organism('Human');

o.print()


这是未定义的。为什么?这应该表明,因为它是有机体的一种方法。
 print()没有显示在对象中

最佳答案

当您这样做时:

Organism.prototype = new Mammal();  //Organism inherits Mammal


您替换了整个prototype对象,从而清除了先前分配的对象:

Organism.prototype.print = function(){
    return this.orgName;
}




您可以通过更改顺序来修复它,以便将新方法“添加”到继承的原型中:

function Organism(name){
   this.orgName = name;
}

Organism.prototype = new Mammal();  //Organism inherits Mammal

Organism.prototype.print = function(){
    return this.orgName;
}




顺便说一句,仅供参考,您应该考虑改为使用Organism.prototype = Object.create(Mammal.prototype);,并且也应该调用基础对象的构造函数。有关示例,请参见here on MDN

10-08 17:41