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: