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

1
  • 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 to learn how to set up inheritance properly. Commented Jan 6, 2015 at 0:45

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

This not a jQuery question by any tag, so why are you using jQuery?
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.
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.
Your indentation on the print function is off by 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.