Blog

Inheritance in JavaScript

Apr 17, 2009 | English | By Crysfel | No Comments | Leer en Espaol

JavaScript has a unique way of object creation and inheritance, this concept is called “prototypal inheritance”, basically an object can inherit methods and properties to other objects creating a prototype to create new objects.

Inheritance in JavaScript
Author: Crysfel

I'm a software developer with 6+ years of experience, when I'm not developing software I may be writing a tutorial, you can follow me on twitter

The prototypal inheritance can be done by using the property “prototype” that you can find in all the objects. In JavaScript the inheritance is simple but with some effort you can obtain the multiple inheritance; in this chapter we will show how to do a simple inheritance.

It is important to remember that the property “prototype” can only inherit from other objects and not prototypes or constructors. Let’s see the next example to understand this better:

//Super "class"
var Animal = function(type){
	this.type = type;
}

Animal.prototype.getType = function(){
	return this.type;
}

var Dog = function(options){
	this.breed = options.breed;
}

//Inheritance
Dog.prototype = new Animal('Dog');

//attach methods to the Dog "class"
Dog.prototype.run = function(){
	console.debug('the '+this.breed+' '+this.type+' is running!');
}
//new instance
var beagle = new Dog({breed:'Beagle'});

//calling a method of the super "class"
console.debug(beagle.getType());
beagle.run();

The most important part of the previous example is where we do the inheritance, “Dog.prototype = new Animal(‘Dog’);”. The variable Dog makes a reference to the constructor of the object Dog, “new Animal()” is creating an Animal object which is assign to the prototype of the constructor of the “Dog” object; in this way the Dog object will have all the methods and properties of the Animal object when new instances are created.

Conclusion

The simple inheritance is something we will use when we develop components, that’s why is important to understand this concept.

Leave a Reply







Updates

RSS

Subscribe to our feeds to receive updates of our newest posts and free tutorials.

Site search

Maybe we have what you need, would you like to search first?

Donations

Would you buy me a cup of coffee? I am sharing my knowledge and time with you, help this project grow. Thank you!