user544079
user544079

Reputation: 16629

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

This comes as undefined. Why? this should show since it is a method of class Organism. print() does not show up in the object

Upvotes: 0

Views: 49

Answers (2)

xdhmoore
xdhmoore

Reputation: 9876

When you assign

Organism.prototype = new Mammal();

you are clobbering the Organism.prototype object that had the print function on it. Try this instead for your inheritance:

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 707318

When you do:

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

you replace the entire prototype object, thus wiping out the previously assigned:

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

You can fix it by changing the order so you "add" your new method to the inherited prototype:

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

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

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

FYI as an aside, you should be thinking about using Organism.prototype = Object.create(Mammal.prototype); instead and you should be calling the constructor of the base object too. See here on MDN for examples.

Upvotes: 3

Related Questions