Inheritance in JavaScript
Apr 17, 2009 | English | By Crysfel | 1 Comment | Leer en EspañolJavaScript 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.
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.





Commercial ExtJs and Sencha Touch Themes


This one would have been more elaborative and informative if we have an example of subclass overriding the super method and then calling super’s method even when it is overridden.
I believe, that would bring in good shape to this tutorial.