POLYMORPHISM

Polymorphism is a fundamental concept in object-oriented programming (OOP) that refers to the ability of different objects to respond to the same method call in different ways. In JavaScript, polymorphism is achieved by using function overloading and function overriding.

Function overloading refers to the ability of a function to have multiple implementations based on the number and/or types of arguments passed to it.

JavaScript does not support function overloading natively, however, you can achieve similar functionality by using the arguments object and checking the number and/or types of arguments passed to the function.

Function overriding refers to the ability of a subclass to provide a different implementation of a method that is already provided by its superclass. In JavaScript, this can be achieved by reassigning the prototype of the subclass.

For example, consider the following code:

app/page.tsx
1class Shape {
2    constructor(name) {
3        this.name = name;
4    }
5    draw() {
6        console.log(`Drawing a ${this.name}`);
7    }
8}
9
10class Circle extends Shape {
11    draw() {
12        console.log(`Drawing a Circle`);
13    }
14}
15
16class Square extends Shape {
17    draw() {
18        console.log(`Drawing a Square`);
19    }
20}
21
22let shape = new Shape("Shape");
23let circle = new Circle();
24let square = new Square();
25
26shape.draw(); //Drawing a Shape
27circle.draw(); //Drawing a Circle
28square.draw(); //Drawing a Square
29

In this example, the draw() method is overridden in the subclasses Circle and Square, providing a different implementation of the method that is already provided by the superclass Shape.

Conclusion

Polymorphism is a fundamental concept in OOP that refers to the ability of different objects to respond to the same method call in different ways.