Can I use jQuery.extend to simulate method overloads?

I am very familiar with jQuery. I am trying to write general methods for my own purpose. The following is an example:

$.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 expander name and pass different parameters, such as method overload?

+6
javascript jquery
source share
3 answers

You are trying to do some type of what is called when the method overloads in some languages.

JavaScript does not support it in this way.

JavaScript is very versatile and allows you to use this feature in many ways.

In your specific example, your add function, I would recommend that you create a function that takes an arbitrary number of parameters using arguments .

 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 a more complex method overload, you can determine the number of arguments passed and their 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 out the following article, it contains a very interesting method that uses some functions of the JavaScript language, such as closing, a functional application, etc., to simulate method overloads:

+15
source share

I think it’ll just replace the first add property with the 2nd add property that you defined. This is useful when developing plugins and you want to provide a list of reasonable default values ​​for the configuration object.

+3
source share

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

You can use the setting of variable arguments in your function using "arguments", or you can simply define your function as you have in the second statement (with three parameters), and just check if the third parameter is undefined, If the argument is not specified, it is set as undefined, and you can just check it (this is not the same as null), which could be simpler than using the arguments object.

0
source share

All Articles