Hello-World
Hello-World

Reputation: 9545

javascript inherit from a class

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

Upvotes: 1

Views: 171

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

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

Upvotes: 2

Related Questions