Sunday, February 16, 2014

Inheritance via prototypes, JavaScript

One of the most prominent concept of Object oriented programming is inheritance. By definition, inheritance is the act of inheriting the properties of Child class from the Parent class. For instance, say we have  class Animal, which have two properties, hasFourLegs and hasTail. For all the categories of animals, these properties should possess the value as true.
Further suppose we have another class as Cat. Since Cat is also an animal, it should inherit both the properties which are defined for Animals, plus an additional property, canSeeInDark, should also be there which is true specifically for the Cat. 

The implementation of the above classes in JavaScript is as follows:

   1: var Animal = function(){}
   2:  
   3: Animal.prototype.hasFourLegs = true;
   4: Animal.prototype.hasTail = true;
   5:  
   6: var Cat = function(){}
   7:  
   8: Cat.prototype.canSeeInDark = true;

Above code do shows the two classes and their properties, Animal and Cat, but there is no sign of inheritance. If you create an instance of class Cat and try to access any of the property of Class Animal, JavaScript would return ‘undefined’.


   1: var tom = new Cat();
   2: console.log(tom.hasTail); //undefined property hasTail
To enable inheritance between Cat and Animal, following line of code would suffice.


   1: Cat.prototype = Animal.prototype;

This is called prototype chaining and it says that, every prototype properties of class Cat should be equal to every prototype properties of class Animal. Again, if you were to call tom.hasTail now, the output this time, would be true.

This is how one can enable inheritance in JavaScript using prototype chain.

I hope this post would be useful.

Happy Coding!!!

Share this post

1 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top