views:

35

answers:

6

hi,

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?

+1  A: 

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
  }
}
Pablo Fernandez
+1 to everyone!! (since you all answered at the same time)
Blair McMillan
+1  A: 

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
    }
};
nickf
+2  A: 

Javascript doesn't support method overloading (at least in the traditional sense) is the reason.

The second function is overwriting the first.

cletus
+1  A: 

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);
    }
}
jvenema
+1  A: 

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.

Vincent Ramdhanie
+1  A: 
$.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.

inkedmn
Thanks all! I thought, this is working like in java, where I can write overloaded methods! –