How To Use Polymorphism Using JavaScript?

Nov 25, 2021 . Admin



Hello Friends,

Now let's see example of how to use polymorphism example.We will check how to use polymorphism. This is a short guide on use polymorphism in javascript. Here you will learn how to use javascript polymorphism. Let's get started with how to use polymorphism in javascript.

Here i will give you many example how to use polymorphism using javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <title>How To Use Polymorphism Using JavaScript? - MyWebtuts.com</title>
    </head>
    <body>
        <h3>How To Use Polymorphism Using JavaScript? - MyWebtuts.com</h3>
        <script>
            class A1
            {
                display()
                {
                    document.writeln("A1 is invoked<br>");
                }
            }
            class B1 extends A1
            {
                display()
                {
                    document.writeln("B1 is invoked");
                }
            }

            var temp = [new A1(), new B1()]
            temp.forEach(function(msg)
            {
                msg.display();
            });
        </script>
    </body>
</html>
Output :
A1 is invoked
B1 is invoked
Example : 2
<!DOCTYPE html>
<html>
    <head>
        <title>How To Use Polymorphism Using JavaScript? - MyWebtuts.com</title>
    </head>
    <body>
        <h3>How To Use Polymorphism Using JavaScript? - MyWebtuts.com</h3>

        <script>
            function Temp()
            {
            }
            Temp.prototype.display=function()
            {
                return "Temp is invoked";
            }
            function test()
            {

            }
            test.prototype=Object.create(Temp.prototype);

            var a1 = [new Temp(), new test()]

            a1.forEach(function(a2)
            {
                document.writeln(a2.display()+"<br>");
            });
        </script>
    </body>
</html>
Output :
Temp is invoked
Temp is invoked

It will help you...

#Javascript