Javascript Inheritance Example

Inheritance is when a child object inherits(use or access) the properties and methods from a parent object. For example, an Animal object is a parent object and it has the property name, and method speak. If a Dog object inherits from the Animal object, the Dog object doesn’t have to redefine the property name and the method speak, since they are already defined the in the parent object. However, the Dog object is free to redefine the properties or methods that are already defined in the parent class in order to override the parent behavior.

Javascript Inheritance Example 1, this example looks similar to classical languages such as Java and c++

function Animal(name)
{
	this.name=name;

	this.eat = function(food)
	{
		console.log(name + " is eating " + food + "...");
	}

	this.speak = function()
	{
		console.log("My name is " + name);
	}

}

function Dog(name,breed)
{
	this.breed = breed;
	Animal.call(this, name);
	var parentSpeak = this.speak;
	//Overriding the parent speak function
	this.speak = function()
	{
		console.log("I am a " + breed);
		parentSpeak();
	}
}
Dog.prototype = new Animal(); //Inherit from Animal

var d = new Dog("Bonny", "Siberian Husky");
d.speak();
d.eat("bone");
console.log(d instanceof Animal);//true
console.log(d instanceof Dog);//true

Javascript Inheritance Example 2, intensive use of the prototype property.

function Bird(name)
{
	this.name = name;
}

Bird.prototype.eat = function(food)
	{
		console.log(this.name + " is eating " + food + " ...");
	}
Bird.prototype.speak = function()
	{
		console.log("My name is "+ this.name);
	}

var Eagle = function(name, breed)
{
	this.breed = breed;
	Bird.call(this, name);
}

Eagle.prototype = new Bird();//Inherit from Animal

Eagle.prototype.speak = function()//Overriding the parent speak function
	{
		console.log("I am a " + this.breed);
		this.constructor.prototype.speak.call(this);
	}

var e = new Eagle("Rocki", "Bald Eagle");
e.speak();
e.eat("fish");
console.log(e instanceof Bird); //true
console.log(e instanceof Eagle); //true

demo, Right click on the mouse, Inspect Element, Click console.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search