JavaScript – Polymorphism


What is polymorphism ?

Polymorphism is a core concept of an object-oriented programming concept.

A certain form is modified into several other different forms based on condition.

What is polymorphism in javascript ?

Polymorphism in javascript is to perform a single action in different forms.

It calls the same method on different JavaScript objects.

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

Why polymorphism in javascript ?

Polymorphism handles the re usability of code and makes the program more flexible and malleable.

It handles the way that one type of code can be substituted by other compatible ones if they satisfy a public interface.

It helps with data hiding and modularity.

Javascript online course !!!

Click to Learn More about – Javascript online learning

How does polymorphism work in javascript ?


1. Simple polymorphism

Example :

<script>
                        // same method is called in different forms
                        class parentClass{
                                printObj(){
                                        document.writeln("This is called inside parentClass <br/>");
                                }
                        }
                        class childClass extends parentClass{
                        }
                        var a = new parentClass();
                        a.printObj();
                        var b = new childClass();
                        b.printObj();
                </script>

Output :


2. Simple polymorphism with same method names.

Example :

<script>
			// differennt methods with same name is called.
			class parentClass{
				printObj(){
					document.writeln("<b>parentClass : </b>This is called inside parentClass <br/>");
				}
			}
			class childClass extends parentClass{
				printObj(){
					document.writeln("<b>childClass : </b>This is called inside childClass <br/>");
                                }
			}
			var a = new parentClass();
			a.printObj();
			var b = new childClass();
			b.printObj();
		</script>

Output :

3. Prototype function

Example :

<script>
                        // same prototype function is called twice
                        function parentFunction(){
                        }
                        function childFunction(){
                        }
                        parentFunction.prototype.show = function(){
                                return "<b>parentFunction : </b>Prototype parentFunction is invoked<br/>";
                        }
                        childFunction.prototype = Object.create(parentFunction.prototype);
                        var a = new parentFunction();
                        var b = new childFunction();
                        document.write(a.show());
                        document.write(b.show());
                </script>

Output: