Polymorphism in JavaScript
Polymorphism in JavaScript — method override and universal interface
Polymorphism is a programming principle that allows objects of different classes to have the same method with unique implementations. In JavaScript, polymorphism is primarily expressed through method overriding and interface-like patterns.
This is important when the same operation (for example, draw()
) can be implemented differently across different objects.
When the same method is defined in both parent and child classes with different implementations, this is polymorphism.
class Shape { draw() { console.log('Drawing a generic shape'); } }
class Circle extends Shape { draw() { console.log('Drawing a Circle'); } }
class Square extends Shape { draw() { console.log('Drawing a Square'); } }
Now we can write code that works with all shapes without knowing their specific types.
const shapes = [new Circle(), new Square(), new Shape()];
shapes.forEach(shape => shape.draw()); // Drawing a Circle // Drawing a Square // Drawing a generic shape
This is the power of polymorphism: the code is written at the parent class level, but the behavior is determined by the actual object type.
JavaScript doesn't have an interface
keyword, but we can create implicit interfaces through design. For example, all figures can have an area()
method with different calculations.
class Rectangle { constructor(w, h) { this.w = w; this.h = h; }
area() { return this.w * this.h; } }
class Triangle { constructor(b, h) { this.b = b; this.h = h; }
area() { return 0.5 * this.b * this.h; } }
const figures = [new Rectangle(4, 5), new Triangle(4, 5)];
figures.forEach(f => { console.log(f.area()); }); // 20 // 10
The only requirement is that all have an area()
method - this is polymorphic design without inheritance.
Use polymorphism when:
draw()
for all figures)This supports the Open/Closed Principle from SOLID OOP principles.
Polymorphism allows developers to work at the interface level without needing to know the internal structure of specific objects. In JavaScript, it can be implemented using classes.
In the next part, we'll discuss how to create base classes and use abstract classes in JavaScript, even though the language doesn't have direct syntax for them.