JS Inheritance
by path411
JavaScript
// Base class
function Animal() {
this.Sound = "Roar";
}
Animal.prototype.Speak = function() {
return this.Sound;
};
Animal.prototype.Jump = function() {
return "Jump";
};
// Inherit Method
function Dog() {
Animal.apply(this);
this.Sound = "Bark";
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Animal;
// Inherit Property
function Lion() {
Animal.apply(this);
}
Lion.prototype = new Animal();
Lion.prototype.constructor = Animal;
// Inherit and add new Method
function Tiger() {
Animal.apply(this);
}
Tiger.prototype = new Animal();
Tiger.prototype.constructor = Animal;
Tiger.prototype.Eat = function() {
return "omnom";
}
// Call base
Tiger.prototype.Jump = function() {
var base = this.prototype.Jump();
return "Tiger"+base;
};
// Add new method to base class later
Animal.prototype.Run = function() {
return "zoom";
}
var spike = new Dog();
document.write(spike.Speak()); // Returns "Bark"
document.write("<br />");
var simba = new Lion();
document.write(simba.Speak()); // Returns "Roar"
document.write("<br />");
var jaz = new Tiger();
document.write(jaz.Speak()); // Returns "Roar"
document.write("<br />");
document.write(jaz.Eat()); // Returns "omnom"
document.write("<br />");
document.write(jaz.Run()); // Returns "zoom"
document.write("<br />");
document.write(jaz.Jump()); // Returns "TigerJump"
document.write("<br />");