How to implement Polymorphism in JavaScript?



Polymorphism

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.

Example

Live Demo

<html>
<body>
<script>
   var game = function () {}
      game.prototype.select = function()
   {
      return " i love games and sports"
   }
   var cricket = function() {}
   cricket.prototype = Object.create(game.prototype);
   cricket.prototype.select = 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
   tennis.prototype.select = 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()];
   games.forEach(function(game){
      document.write(game.select());
    document.write("</br>");
   });
</script>
</body>
</html>

Output

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

Advertisements