JavaScript OOPs Polymorphism

Polymorphism is a fundamental principle within the object-oriented programming paradigm that enables the execution of a single operation in various forms. This capability allows for the invocation of the same method across diverse JavaScript objects. Given that JavaScript lacks strict type safety, it permits the passing of any data type as arguments to these methods.

JavaScript Polymorphism Example 1

Consider an illustration in which an instance of a child class calls a method defined in its parent class.

Example

<script>

class A

  {

     display()

    {

      document.writeln("A is invoked");

    }

  }

class B extends A

  {

  }

var b=new B();

b.display();

</script>

Output:

Output

A is invoked

Example 2

Consider an illustration where both a parent class and a child class feature an identical method. In this scenario, an instance of the child class will call the method from both the parent and the child classes.

Example

<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>

Output:

Output

A is invoked

B is invoked

Example 3

Let us examine the identical example utilizing a prototype-based methodology.

Example

<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>

Output:

Output

A is invoked

B is invoked

Input Required

This code uses input(). Please provide values below: