Sunday, April 21, 2013

Javascript: Inheritance in Object Oriented Programming


Inheritance allows one class to see and use the methods and properties of another class. Let's create a class called Animal, along with a sayName method:

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

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

// here's a code to test the above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

Wouldn't it be cool if we created a Penguin class? Let's do that so that we can give it some methods unique only to a penguin and not confuse it with the Animal class.

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

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

We seemed to have reused a lot of the same code as the Animal class. This goes against the "DRY" principle--aka "don't repeat yourself"! We're going to create a new Penguin class, but we're going only take a name parameter, and within the constructor itself, set this.numLegs to 2.

function Penguin (name) {
    this.name = name;
    this.numLegs = 2

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();

Now we're going to create an Emperor class that takes a single name parameter and sets its name property to be this value.

// create your Emperor class and make it inherit from Penguin
function Emperor (name) {
    this.name = name;
}

Emperor.prototype = new Penguin();
// create an "emperor" object and print the number of legs it has
var emperor = new Emperor("Mr. McWaddle");
console.log(emperor.numLegs);

The "prototype chain" in Javascript sort of like a food chain. If JavaScript encounters something it can't find it the current class's methods or properties, it looks up the prototype chain to see if it's defined in a class that it inherits from. This keeps going upwards until it stops all the way at the top: the Object.prototype. All classes inherit directly from Object, unless we change the class's prototype.

// original classes
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
    this.isAlive = true;
}
function Penguin(name)
    this.name = name;
    this.numLegs = 2;
}
function Emperor(name) {
    this.name = name;
    this.saying = "Waddle waddle";
}

// set up the prototype chain
Penguin.prototype = name Animal();
Emperor.prototype = new Penguin();

var myEmperor = new Emperor("Jules");

console.log( myEmperor.saying ); // should print "Waddle waddle"
console.log( myEmperor.numLegs ); // should print 2
console.log( myEmperor.isAlive ); // should print true

No comments:

Post a Comment