1

Im learning inheritance. In the code below

1)penguin inherits from Animal

2)when I call penguin.sayName(); why does it output "Hi my name is undefined";

function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;


}
Animal.prototype.sayName = function(){
  console.log("Hi my name is " + this.name);
};


function Penguin(){}

Penguin.prototype = new Animal();

var penguin = new Penguin("Captain Cook", 2);
penguin.sayName();

1 Answer 1

2

You need to add the name and numLegs properties to the penguin object via the function constructor. These two properties are specific to the Animal object and will not be assigned simply by calling the Penguin constructor.

function Penguin(name,numLegs){
  this.name = name;
  this.numLegs = numLegs.
}

Working Example: http://jsfiddle.net/5A7hH/

You could also use the constructor on the prototype chain, which is similar to calls of the super() constructor in Java.

function Penguin(name,numLegs){
   this.constructor(name,numLegs);
}
Sign up to request clarification or add additional context in comments.

8 Comments

thanks - but I still a little unsure, if its inheriting from Animal why don't those automatically get used?
@Hello-World It doesn't get used because the Animal constructor is never called unless explicitly stated, as illustrated in the second example. In your example, the name and numLegs properties never get assigned since the Parents constructor is not called. This is pretty standard in OO languages. Are you familiar with Java? Think about how the call to super is required for every class that extends another.
Not sure why but typically constructor will not get inherited by child object. This apply to C#, Java and etc.
Kevin Bowersox - wow - thank you - I'm still new to all of this. which is the best way - Is your first example the most correct?
Please note that this.constructor(name,numLegs); only works because the constructor property is overridden to point to Animal in Penguin.prototype = new Animal();. Usually the constructor function points to the constructor function itself, i.e. to Penguin, so it does not behave like super. A better approach would be Animal.apply(this, arguments).
|

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.