Sunday, September 22, 2019

What is Polymorphism in JavaScript? Explain It with example.

The polymorphism is a core concept of an object-oriented paradigm that provides a way to perform a single action in different forms. 

It provides an ability to call the same method on different JavaScript objects. 

As JavaScript is not a type-safe language, we can pass any type of data members with the methods.

JavaScript Polymorphism Example 1

Let's see an example where a child class object invokes the parent class method.

  1. <script>  
  2. class A  
  3.   {  
  4.      display()  
  5.     {  
  6.       document.writeln("A is invoked");  
  7.     }  
  8.   }  
  9. class B extends A  
  10.   {  
  11.   }  
  12. var b=new B();  
  13. b.display();  
  14. </script>  

Output:

A is invoked

Example 2

Let's see an example where a child and parent class contains the same method. Here, the object of child class invokes both classes method.

  1. <script>  
  2. class A  
  3.   {  
  4.      display()  
  5.     {  
  6.       document.writeln("A is invoked<br>");  
  7.     }  
  8.   }  
  9. class B extends A  
  10.   {  
  11.     display()  
  12.     {  
  13.       document.writeln("B is invoked");  
  14.     }  
  15.   }  
  16.   
  17. var a=[new A(), new B()]  
  18. a.forEach(function(msg)  
  19. {  
  20. msg.display();  
  21. });  
  22. </script>  

Output:
A is invoked
B is invoked

Example 3

Let's see the same example with prototype-based approach.

  1. <script>  
  2. function A()  
  3. {  
  4. }  
  5. A.prototype.display=function()  
  6. {  
  7.   return "A is invoked";  
  8. }  
  9. function B()  
  10. {  
  11.     
  12. }  
  13.   
  14. B.prototype=Object.create(A.prototype);  
  15.   
  16. var a=[new A(), new B()]  
  17.   
  18. a.forEach(function(msg)  
  19. {  
  20.   document.writeln(msg.display()+"<br>");  
  21. });  
  22. <script>  

Output:
A is invoked
B is invoked

No comments:

Post a Comment