I've got 2 jQuery functions. One calls the other (in theory...). These are:
$.testFunction = function(arg1){
alert("testFunction(arg1)");
$.testFunction(arg1, "");
}
$.testFunction = function(arg1, arg2){
alert("testFunction(arg1, arg2)");
alert("arg1: " + arg1 + "\narg2: " + arg2);
}
I've got two functions, because when I haven't got the second parameter to pass, I'd like to call the simple version of them. But when I call like this:
$.testFunction("first param");
alert("Before second call");
$.testFunction("first param", "second param");
It's always calling the second one, and (in the alert window) puts: "testFunction(arg1, arg2)" then "arg1: first param arg2: undefined". Why is working like this? Why is not the first function being called when I pass only one parameter?
6 Answers 6
Javascript doesn't support method overloading (at least in the traditional sense) is the reason.
The second function is overwriting the first.
Comments
$.testFunction = function(arg1, arg2){
if(arg2 === null || arg2 === undefined){
// run the first version
}else{
// run the second version
}
}
Try that instead - this way, you only have one function and you just check for the presence of the second param before executing the body.
1 Comment
Uhh - you're overwriting the first function immediately. Here's the equivalent of what you're doing:
x = "foo";
x = "bar";
alert(x); // 'bar' -- "why isn't this foo????!?!"
A good option would be to write a single function which behaves differently depending on the number of arguments passed to it:
var testFunction = function(a, b) {
if (b === undefined) {
// no second parameter
}
};
Comments
You're overwriting the function. Javascript has no concept of overloaded functions.
Instead, functions take an arbitrary number of parameters, and you can access them via the special "arguments" property.
$.testFunction = function(arg1, arg2){
if(arguments.length == 2){
alert("arg1: " + arg1 + "\narg2: " + arg2);
}else{
alert("arg1: " + arg1);
}
}
Comments
You are redefining the function and effectively replacing the first single argument function with a two argument function. Now you really only have one function.
You might want to look at this article which might help with the overloading.
Comments
There's no function overloading in javascript, your second function replaces the first one.
You could achieve something similar inspecting the arguments object like this:
$.testFunction = function(arg1, arg2){
if(arguments.length == 1){
// handle one argument
}else if(arguments.length == 2{
// handle 2 arguments
}
}