Polymorphism-tutorial
Polymorphism is a core concept of object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common parent class.
In JavaScript, polymorphism is achieved using
Lets see what this means and how it works.
How Polymorphism Works in JavaScript
Output
.webp)
In JavaScript, polymorphism is achieved using
- Prototype-based inheritance
- Dynamic typing
Lets see what this means and how it works.
How Polymorphism Works in JavaScript
Prototype-Based Inheritance
Dynamic Typing
Example: Simple Inheritance and Method Call
- JavaScript objects can inherit properties and methods from other objects through the prototype chain.
- When an object does not have a method, JavaScript looks up in its prototype to find it.
Dynamic Typing
- JavaScript is dynamically typed, so variables can hold different types of objects at runtime.
- This makes it possible to treat different objects as the same type if they share methods or properties.
Example: Simple Inheritance and Method Call
<!DOCTYPE html><html>
<body>
<script> class A { display() { document.writeln("A is invoked"); } } class B extends A { }
var b = new B(); b.display(); // Calls method from class A </script>
</body>
</html>
Output
.webp)
Explanation
Class B inherits from A and uses its display() method.
Example: Overriding Methods (Polymorphism)
Output
.webp)
Class B inherits from A and uses its display() method.
Example: Overriding Methods (Polymorphism)
<!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 arr = [new A(), new B()];
arr.forEach(function (item) { item.display(); }); </script>
</body>
</html>
Output
.webp)
Explanation
- Both A and B have a method named display().
- When we loop through the array, each object calls its own version of display().
- This is polymorphism: the same method name behaving differently based on the object type.