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
addfunction, I would recommend you to make a function that accepts an arbitrary number of parameters, using theargumentsobject.Then you can pass any number of arguments:
For more complex method overloading you can detect the number of arguments passed and its types, for example:
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: