Loading

Polymorphism

  • Polymorphism is a fundamental concept in object-oriented programming.
  • It allows objects of different classes to be treated as objects of a common superclass. 
  • polymorphism is achieved through the use of prototype-based inheritance and dynamic typing.

How polymorphism works

Prototype-Based Inheritance: 

  • JavaScript uses prototypes for inheritance. Objects in JavaScript are linked to a prototype object, and when you access a property or method on an object, the runtime will look up the prototype chain to find the property or method if it doesn't exist on the object itself. This allows you to create objects that share common properties and methods.

Dynamic Typing:

  •  JavaScript is a dynamically typed language, which means that the type of a variable or object is determined at runtime rather than compile-time. 
  • This flexibility allows you to assign different types of objects to a variable and still call methods or access properties on them.

Example:

<!DOCTYPE html>
<html>

<body>

    <script>
        class A {
            display() {
                document.writeln("A is invoked");
            }
        }
        class B extends A {
        }
        var b = new B();
        b.display();
    </script>

</body>

</html>

Output:

A is invoked

Example:

<!DOCTYPE html>
<html>

<body>

    <script>
        class A {
            display() {
                document.writeln("A is invoked<br>");
            }
        }
        class B extends A {
            display() {
                document.writeln("B is invoked");
            }
        }

        var a = [new A(), new B()]
        a.forEach(function (msg) {
            msg.display();
        });
    </script>

</body>

</html>

Output:

A is invoked
B is invoked

In the above example, child and parent classes contain the same method.