Home >>Javascript Tutorial >JavaScript Polymorphism
The JavaScript polymorphism is basically a core concept of object-oriented paradigm providing a way so that a single action can be performed in different forms. Polymorphism provides an ability to call the very same method on various JavaScript objects. Since JavaScript is not a type-safe language, users can pass any type of data members with the methods.
1. Here is an example where a child class object invokes the parent class method:
<script> class A { display() { document.writeln("space is invoked"); } } class B extends A { } var b=new B(); b.display(); </script>
2. In the following example, a child and parent class contains the same method. This example depicts that the object of child class invokes both classes method.
<script> class A { display() { document.writeln("space is invoked<br>"); } } class B extends A { display() { document.writeln("spacex is invoked"); } } var a=[new A(), new B()] a.forEach(function(msg) { msg.display(); }); </script>
3. Here is an example depicting with prototype-based approach.
<script> function A() { } A.prototype.display=function() { return "A is invoked"; } function B() { } B.prototype=Object.create(A.prototype); var a=[new A(), new B()] a.forEach(function(msg) { document.writeln(msg.display()+"<br>"); }); </script>