JavaScript Inheritance

by Kushal Jayswal

JavaScript

//QUESTION: What is javascript inheritance ?

//A is a type of B.
//In JavaScript You must use a special object called prototype.

function Animal() {} // This is the Animal *Type*
Animal.prototype.eat = function (){
    alert('All animals can eat!');
};


function Bird() {} // Declaring a Bird *Type*
Bird.prototype = new Animal(); // Birds inherit from Animal
Bird.prototype.fly = function () {
    alert('Birds are special, they can fly!');
};

//The effect of this is that any Birds you create(called an instance of Bird) all have the properties of Animals
var aBird = new Bird(); // Create an instance of the Bird Type
aBird.eat(); // It should alert, so the inheritance worked
aBird.fly(); // Important part of inheritance, Bird is also different to Animal

var anAnimal = new Animal(); // Let’s check an instance of Animal now
anAnimal.eat(); // Alerts, no problem here
anAnimal.fly(); // Error will occur, since only Birds have fly() in its prototype