//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
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.