JavaScript - Polymorphism




JavaScript - Polymorphism

Polymorphism is the presentation of one interface for multiple data types. For example, integers, floats, and doubles are implicitly polymorphic, regardless of their different types, they can all be added, subtracted, multiplied, and so on. In the case of OOP, by making the class responsible for its code as well as its own data, polymorphism can be achieved in that each class has its own function that (once called) behaves properly for any object.

Polymorphism is one of the tenets of Object Oriented Programming (OOP). It is the practice of designing objects to share behaviors and to be able to override shared behaviors with specific ones. Polymorphism takes advantage of inheritance in order to make this happen. In OOP everything is considered to be modeled as an object. This abstraction can be taken all the way down to nuts and bolts for a car, or as broad as simply a car type with a year, make, and model.

To have a polymorphic car scenario there would be the base car type, and then there would subclasses which would inherit from car and provide their own behaviors on top of the basic behaviors a car would have. For example, a subclass could be TowTruck which would still have a year make and model, but might also have some extra behaviors and properties which could be as basic as a flag for IsTowing to as complicated as the specifics of the lift.

Polymorphism is the practice of designing objects such that they share behaviors and are able to override shared behaviors with specific ones or which give best results. In JavaScript, Polymorphism takes advantage of inheritance in order to make this happen. Polymorphism is another important tenet of Object Oriented Language. Polymorphism basically represents that in a case where there are more than one function with same name and we call it (function name) on the object, then automatically that function is called that best suits the object. In various languages this is represented and fulfilled by following 2 ways -- Method Overloading and Method Overriding.

We need to remember that Polymorphism is best represented by these 2 pathways and in JavaScript also we will consider these ways and compare how can these bring in Polymorphism in JavaScript. Method Overloading basically takes help of types of arguments to match the correct function, while Method Overriding takes closest one to the object rather than inherited one to call the function. As, in JavaScript, types of arguments are not bound to be same as called in function or JS will stop processing further on ... if types are not matched. So this one does not match nature of JavaScript. Lets look onto 2nd option -- Method Overriding. Due to inheritance (Prototypal, of course), it might happen that via Prototype Chain, there might be more than one Methods with the same name (say alpha). So, due to laws of Prototypal Chain, the one closes to the object in the Prototype Chain will be picked up shadowing others. Thus, though there may be multiple functions (of same name) present in the Prototype Chain, but closest to the object will be picked up representing Polymorphism in JavaScript.

Example

<script>  
class A  
  {  
     display()  
    {  
      document.writeln("A is invoked");  
    }  
  }  
class B extends A  
  {  
  }  
var b=new B();  
b.display();  
</script>  

Output

A is invoked

What is an JavaScript Polymorphism ?

Polymorphism allows us to define the same method in different objects and provides the ability to call them depending upon the object. If we consider the above example, the method run() is common in both the child objects. The user can select an object of any of the child classes at runtime, the JavaScript will call then the run() method accordingly.

There are two approaches by which we can use Polymorphism in JavaScript. One by checking the argument types or by another approach by tracking an object at the last argument of a function.

Polymorphism by Checking Argument Type

 function CatStrings(p1, p2, p3)
 {
   var s = p1;
   if(typeof p2 !== "undefined") {s += p2;}
   if(typeof p3 !== "undefined") {s += p3;}
   return s;
 };

 CatStrings("one");        // result = one
 CatStrings("one",2);      // result = one2
 CatStrings("one",2,true); // result = one2true

Polymorphism by Tracking an object

 function foo(a, b, opts) {
 }

 foo(1, 2, {"method":"add"});
 foo(3, 4, {"test":"equals", "bar":"tree"});

Polymorphism in Typescript

However TypeScript end result is Plain JavaScript, we can only provide the single method block. Through the use of conditional statements −

class Car{
    setSpeed(message: string);
    setSpeed(message: number);
    setSpeed(message: boolean);
    setSpeed(message: any) {
        if (typeof message === "string") {
            alert(message);
        } else if (typeof message === "number") {
            alert("The number provided was: " + message);
        } else if (typeof message === "boolean") {
            alert("The boolean value was: " + message);
        } else {
            alert(message);
        }
    }
}

var car = new Car();
car.setSpeed(false);

Polymorphism is one of the main feature of Object Oriented Programming.Polymorphism in Object-Oriented Programming is the ability to create an object that has more than one form. Polymorphism can be used when there is a hierarchy of classes and they are linked by inheritance. JavaScript polymorphism has one feature that is different than other object-oriented languages, as in javascript we can add and override members on the fly, after an object has been created. Also an object can add or lose properties and behaviors over time.

Example

<script type="text/javascript">
  employee = function(name, age) {
    this.name=name;
    this.age=age;
    this.userInfo=function() {
      return "my name is " + this.name + "my age is " +
         + this.age;
    }
  }
  manager = function(name, age, salary){
    this.name=name;
    this.age=age;
    this.salary=salary;
    this.userInfo=function() {
      return "my name is " + this.name + "my age is " +
         + this.age + "my salary is " + this.salary;
    }
  }
  function getInfo(obj) {
    document.write(obj.getInfo()+"<br>");
  }
  var employee = new employee('John',80);
  var manager = new manager('Peter',80,50000);
  getInfo(manager);
  getInfo(employee);
 
</script>

Polymorphism in the ability to exist and appear in many forms.

Derived objects or subclass may be treated as objects of a base class such as collections of arrays. Derived objects can override methods of a base object by providing their own implementations.

Let's explain this concepts in JavaScript while building upon the Shape object and its derived objects from the inheritance post.

A Child object or subclass or derived object may be treated as a parent objects of a base class.