Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use jQuery.extend to simulate method overloading?

I'm quite familiar with jQuery. I'm trying to write common methods for my own purpose. Here is a sample below:

$.extend({
    add  : function(a, b)
           {
             return a + b;
           },

    add  : function(a, b, c)
           {
             return a + b + c;
           }
   });

Is the above scenario possible? Can I use the same extender name and pass different parameters, like method overloading?

like image 949
superachu Avatar asked Oct 23 '09 04:10

superachu


People also ask

What is the use of jQuery extend?

jQuery | extend() method This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object.

Why function overloading is not possible in JavaScript?

There is no real function overloading in JavaScript since it allows to pass any number of parameters of any type. You have to check inside the function how many arguments have been passed and what type they are.

Can JavaScript have same function name with different parameters?

You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same. In the above example, we have the same function add() with two function declarations and one function implementation.


1 Answers

You are trying to do some type of what is called in some languages method overloading.

JavaScript doesn't supports it in that way.

JavaScript is very versatile and lets you achieve this kind of feature in different ways.

For your particular example, your add function, I would recommend you to make a function that accepts an arbitrary number of parameters, using the arguments object.

jQuery.extend(jQuery, {
  add: function (/*arg1, arg2, ..., argN*/) {
    var result = 0;

    $.each(arguments, function () {
      result += this;
    });

    return result;
  }
});

Then you can pass any number of arguments:

alert(jQuery.add(1,2,3,4)); // shows 10

For more complex method overloading you can detect the number of arguments passed and its types, for example:

function test () {
  if (arguments.length == 2) { // if two arguments passed
    if (typeof arguments[0] == 'string' && typeof arguments[1] == 'number') {
      // the first argument is a string and the second a number
    }
  }
  //...
}

Check the following article, it contains a very interesting technique that takes advantage of some JavaScript language features like closures, function application, etc, to mimic method overloading:

  • JavaScript method overloading
like image 111
Christian C. Salvadó Avatar answered Sep 22 '22 07:09

Christian C. Salvadó