0
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

user544079
  • 16,109
  • 42
  • 115
  • 171
  • 1
    *"This comes as undefined."* Can't repro, I get the error `Uncaught TypeError: undefined is not a function`. Also have a look at [this question](http://stackoverflow.com/q/17392857/218196) to learn how to set up inheritance properly. – Felix Kling Jan 06 '15 at 00:45

2 Answers2

3

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

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() 
xdhmoore
  • 8,935
  • 11
  • 47
  • 90
  • This not a jQuery question by any tag, so why are you using jQuery? – jfriend00 Jan 06 '15 at 00:49
  • Cause it's the cat's pajamas. My use of $.extend() isn't really necessary for the answer. Just my preference. `Organism.prototype.print = function(){}` is fine too. – xdhmoore Jan 06 '15 at 00:51
  • The use of *$* as a function identifier is not unique to jQuery in the same way that *\_* is not unique to underscore.js so you should name the library you are using if you use one. – RobG Jan 06 '15 at 00:59
  • Your indentation on the print function is off by 1. – xdhmoore Jan 06 '15 at 01:12