bryguy
bryguy

Reputation: 73

Object prototypes and Inheritance

// the original Animal class and sayName method
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin() {
    this.name = "penguin";
    this.numLegs = 2;
}

// set its prototype to be a new instance of Animal
var penguin = new Animal("Penguin", 2);

penguin.sayName();

The compiler asks me to "Create a new Penguin instance called penguin"...

not sure what I'm doing wrong here

Upvotes: 1

Views: 80

Answers (1)

Chris Pietschmann
Chris Pietschmann

Reputation: 29885

Here's how to make a Penguin object that inherits from Animal using prototypal inheritance in javascript:

// the original Animal class and sayName method
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};


// define a Penguin class
function Penguin() {
    this.name = "penguin";
    this.numLegs = 2;
}
// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();


// Create new Penguin
var penguin = new Penguin();

penguin.sayName(); // outputs "Hi my name is penguin"
var legCount = penguin.numLegs; // outputs 2

Here's an article that explains JavaScript Prototypal Inheritance in detail: http://pietschsoft.com/post/2008/09/JavaScript-Prototypal-Inheritence-Explained-in-Simple-Terms

Upvotes: 1

Related Questions