开发者

Can I use jQuery.extend to simulate method overloading?

开发者 https://www.devze.com 2022-12-09 19:14 出处:网络
I\'m quite familiar with jQuery. I\'m trying to write common methods for my own purpose. Here is a sample below:

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?


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


I think that will just overwrite the first 'add' property with the 2nd 'add' property you defined. This is useful when developing plugins, and want to provide a list of sensible defaults for a config object.


JavaScript does not throw errors if you pass fewer arguments to a function than it is defined to accept.

You can use a variable arguments set-up in your function using "arguments", or you could just define your function as you had in the 2nd statement (with 3 parameters) and simply check if the 3rd parameter is undefined. If an argument isn't supplied, it is set as undefined and you can simply check for that (it's not the same as null) which may be simpler than having to use the arguments object.

0

精彩评论

暂无评论...
验证码 换一张
取 消