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?
jQuery | extend() method This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With