How to implement Polymorphism in JavaScript?


Polymorphism is one of the tenets of Object Oriented Programming (OOP). It helps to design objects in such a way that the they can share or override any behavior with the specific provided objects. Polymorphism takes advantage of inheritance in order to make this happen.

In the following example child objects such as 'cricket' and 'tennis' have overridden the 'select' method called from parent object 'game' and returned a new string respectively as shown in the output. Whereas another child object 'football', instead of overriding the select method, shared(inherited) the method and displayed the parent string as shown in the output.


Live Demo

   var game = function () {} = function()
      return " i love games and sports"
   var cricket = function() {}
   cricket.prototype = Object.create(game.prototype); = function()                //  overridden the select method to display      {                                                         new string.  
      return "i love cricket"
   var tennis = function() {}
   tennis.prototype = Object.create(game.prototype);  // overridden the select method to display new = function()                  string              
      return "i love tennis"
   var football = function() {}
   football.prototype = Object.create(game.prototype);  // shared parent property
   var games = [new game(), new cricket(), new tennis(), new football()];


i love games and sports
i love cricket
i love tennis
i love games and sports