Junior — Middle
How is polymorphism implemented in Node.js?
sobes.tech AI
Answer from AI
Polymorphism in Node.js is implemented through prototype inheritance and JavaScript's dynamic typing.
Main methods:
-
Prototype inheritance: objects can inherit properties and methods from other objects, allowing behavior to be overridden.
-
Constructor functions and classes (ES6+): you can create classes with methods that can be overridden in subclasses.
-
Dynamic typing: functions can accept arguments of different types and behave differently depending on the type or data structure.
Example with classes and method overriding:
class Animal {
speak() {
console.log('Animal makes a sound');
}
}
class Dog extends Animal {
speak() {
console.log('Dog barks');
}
}
const animal = new Animal();
const dog = new Dog();
animal.speak(); // Animal makes a sound
dog.speak(); // Dog barks
Thus, polymorphism in Node.js is achieved through JavaScript's inheritance and method overriding capabilities.