继承 class 未在 Javascript 中获得自己的方法

Inherited class not getting its own methods in Javascript

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() 

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

当你这样做时:

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

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

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

您可以通过更改顺序来修复它,这样您就可以 "add" 将新方法应用于继承的原型:

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

当你分配

Organism.prototype = new Mammal();

您正在破坏具有打印功能的 Organism.prototype 对象。为您的继承试试这个:

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

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

Organism.prototype = Object.create(Mammal.prototype);
Organism.constructor = Mammal;

// or _.extend(), if using underscore
jQuery.extend(Organism.prototype, {
     print: function(){
        return this.orgName;
    }
});

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

o.print()