tags:

views:

69

answers:

5

Does JS support two functions with the same name and different parameters ?

function f1(a, b)
{
// a and b are numbers
}

function f1(a, b, c)
{
// a is a string
//b and c are numbers
}

Can I use those JS function for IE7, FF, Opera with no problem?

+3  A: 

No, you can't use function overloading in JS.

But, you can declare just the version with 3 parameters, and then check whether the third argument === undefined, and provide differentiated behaviour on that basis.

Chris Jester-Young
In the event that the caller passes a 3rd argument but its value is *undefined* this test would fail. Probably better if the function tests **arguments.length** instead.
NVRAM
If the caller uses `undefined` as the 3rd argument, I'd take that to signal that they'd like the function to be treated as though only two were passed in. I don't really see any other legitimate purpose for passing in `undefined`.
Chris Jester-Young
+1  A: 

No, that will not work, only the 2nd function will be defined on your page. Here's a source.

rosscj2533
+1  A: 

No you can't do that ... unless it is OK with you to only have your last definition hold.

jldupont
+1  A: 

Javascript only uses the function that was defined last.

http://weblogs.asp.net/jgalloway/archive/2005/10/02/426345.aspx

You will need to implement your own logic inside the function to determine which parameters were passed in.

geoff
+8  A: 

JavaScript doesn't support what you would call in other languages method overloading, but there are multiple workarounds, like using the arguments object, to check with how many arguments a function has been invoked:

function f1(a, b, c) {
  if (arguments.length == 2) {
    // f1 called with two arguments
  } else if (arguments.length == 3) {
    // f1 called with three arguments
  }
}

Additionally you could type-check your arguments, for Number and String primitives is safe to use the typeof operator:

function f1(a, b, c) {
  if (typeof a == 'number' && typeof b == 'number') {
    // a and b are numbers
  } else if (typeof a == 'string' && typeof b == 'number' &&
             typeof c == 'number') {
    // a is a string, b and c are numbers
  }
}

And there are much more sophisticated techniques like the one in the following article, that takes advantage of some JavaScript language features like closures, function application, etc, to mimic method overloading:

CMS