继承的类没有在Javascript中获取自己的方法

时间:2015-01-06 00:40:31

标签: javascript inheritance

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()没有出现在对象

2 个答案:

答案 0 :(得分:3)

当你这样做时:

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

除了FYI之外,你应该考虑使用Organism.prototype = Object.create(Mammal.prototype);,而你也应该调用基础对象的构造函数。有关示例,请参阅here on MDN

答案 1 :(得分:1)

分配时

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