How to Implement Polymorphism with Primitive Values in Object-Oriented JavaScript?

Estimated read time 1 min read

To implement polymorphism with primitive values in object-oriented JavaScript, you can use the following approach:

  1. Define a method that takes primitive values as parameters, like a number or a string.
  2. Use type checking to determine the type of the value, and perform different actions based on that type.

Example code:

class Animal {
  makeSound(value) {
    if (typeof value === 'number') {
      console.log(`The animal makes ${value} sounds`);
    } else if (typeof value === 'string') {
      console.log(`The animal says ${value}`);
    } else {
      console.log('Invalid input');
    }
  }
}

const animal = new Animal();
animal.makeSound(3); // The animal makes 3 sounds
animal.makeSound('meow'); // The animal says meow
animal.makeSound({}); // Invalid input

Note: This is just an example, you can modify it as per your requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply