Polymorphism in JavaScript

Polymorphism is the ability to create a variable, a function, or an object that has more than one form. In object oriented programing polymorphism is used to call the same method on different objects to have them respond in their own way.

Polymorphism also supports late binding or dynamic binding which determines exact type of object in runtime. This property of polymorphism makes coding much easier. This process is well used in JavaScript, because JavaScript is not type-set. That means we can assign any type of data to a variable.

A simple example is as follows:

var myFunc = polymorph(

        function(a) {

                return "argument any type";

        },

         {i: Number, str: String},//declaring variables

        function(i,str) {

                return "Number and string passed";

        },

         {f: Function, b: Boolean},

        function(f,b) {

                return "Function and boolean passed";

        },

        {f: Function, i: Number},

        function(f,i) {

                return "Function and number passed";

        }

);

alert(myFunc(12)); // "Three arguments version -- any types"

alert(myFunc(5,"myfunc")); // "Number and string passed"

alert(myFunc(function() {}, true)); // "Function and boolean passed"

alert(myFunc(function() {}, 1)); // "Function and number passed"

Above set of codes gives us the basic idea of how the polymorphism works. In this code we can see that we have a library called ‘polymorph’.

Reader can find the library in – https://code.google.com/p/polymorph-js/

This library accepts sub-functions as we denoted in the upper example by simple function() optionally prepended by object. The return value of ‘polymorph()’ function is an actual polymorphic function. In the upper set of codes we have created many sub-functions to pass many different kind of variables. All this sub functions have the same name as function(). These functions are all resided under the same function called myFunc(). Which has invoked the polymorph library.

After passing different type of variables through the sub-functions, we have to call the sub-functions through the main function MyFunc().

This allows you to easily create polymorphic functions (functions which have the same name and differ in number of parameters or their types). JS itself doesn’t support this, so you should manually check number of parameters and their types to perform different actions. This library makes things much easier.You may also create polymorphic methods and constructors.

Now let us see an example of polymorphic method and polymorphic constructor.

Polymorphic Method:

Rectangle.prototype.add = polymorph(

        {len: Number, wid: Number},

        function(len,wid) {

                if(this.len1 > len) this.len1 = len;

                if(this.len2 < len) this.len2 = len;                 
                if(this.wid1 > wid) this.wid1 = wid;

                if(this.wid2 < wid) this.wid2 = wid;

        },

        {x: Point},

        function(x) {

         this.add(x.len, x.wid);

        },

        {rect: Rectangle},

        function(rect) {

                this.add(rect.len1, rect.wid1);

                this.add(rect.len2, rect.wid2);

        }

);

Polymorphic Constructor:

var Rect = polymorph(

        function(Len1, Wid1, len2, wid2) {

                this.len1 = Len1;

                this.wid1 = Wid1;

                this.len2 = len2;

                this.wid2 = wid2;

        },

        {p1: Point, p2: Point},

        function(p1, p2) {

                this.constructor(p1.len, p1.wid, p2.len, p2.wid);

        },

        {len1: Number, wid1: Number},

        function(len1, wid1) {

                this.constructor(len1, wid1, len1, wid1);

        },

        function() {

                this.constructor(0, 0);
        }
);

Rect.prototype.toString = function() {return "("+this.len1+", "+this.wid1+")-("+this.len2+", "+this.wid2+")";

};

polymorphic function has two additional methods: update and inherit. The update method allows you to add more functions, while the inherit method will create new polymorphic function. We will see an example below:

myFunc.update(

        {func: Function, n: Number},

        function(func, n) {

                return "function replaced old one";

        },

        function(a) {

                return "Single-parameter function";

        }

);

alert(myFunc(function() {}, 1)); // function replaced old one

alert(myFunc(function() {})); // Single-parameter function

now we are going to see a piece of basic code for where two same name functions are being called separately.

function foo_x1(obj1,obj2){

    // code

}

function foo_y2(obj1,obj2,obj3,obj4,obj5){

    // code

}

function bar(obj1, obj2, obj3, obj4, obj5) {

    if(arguments.length == 2)

        return foo_x1(obj1, obj2);

    else

        return foo_y2(obj1,obj2,obj3,obj4,obj5);

In the below code we can see that there is three functions present in this snippet by the name of Person, Employee and showInfo . we are going to work with these three functions. In the Person function we have two parameters named age and weight. These two parameters will be called upon from outer the function and printed by this code.

return "I am " + this.age + " years old " + "and weighs " + this.weight +" kilo.";

After this we are going for the next function. And that is Employee. In this function not only two but we are passing three parameters. Age , weight and salary. Though we have already used age and weight parameters beforehand, this time they will be completely different.

And finally we can invoke showinfo() function to call the object.

  function Person(age, weight) {

    this.age=age;

    this.weight=weight;

    this.getInfo=function() {

      return "I am " + this.age + " years old " +

        "and weighs " + this.weight +" kilo.";

    }

  }

  function Employee(age, weight, salary){

    this.salary=salary;

    this.age=age;

    this.weight=weight;

    this.getInfo=function() {

      return "I am " + this.age + " years old " +

        "and weighs " + this.weight +" kilo " +

        "and earns " + this.salary + " dollar.";

    }

  }

  Employee.prototype= new Person();

  Employee.prototype.constructor=Employee;

  function showInfo(obj) {

    document.write(obj.getInfo()+"
");

  }

  var person = new Person(50,90);

  var employee = new Employee(43,80,50000);

  showInfo(person);

  showInfo(employee);

If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:Delivered by FeedBurner

3 thoughts on “Polymorphism in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *