views:

7159

answers:

5

What is the best way (or ways) to fake function overloading in Javascript?

I know it is not possible to overload functions in Javascript as in other languages. If i needed a function with two uses foo(x) and foo(x,y,z) which is the best / preffered way:

  1. Using different names in the first place
  2. Using optional arguments like y = y || 'default'
  3. Using number of arguments
  4. Checking types of arguments
  5. Or how?
+9  A: 

There is no real function overloading in JavaScript since it allowes 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.

Gumbo
John Resig (of jQuery) once tried this, but the attempt was purely academic and didn't provide any real benefit.
scunliffe
+2  A: 

There are two ways you could approach this better:

  1. Pass a dictionary (associative array) if you want to leave a lot of flexibility

  2. Take an object as the argument and use prototype based inheritance to add flexibility.

David in Dakota
This. +1111111111
annakata
+1  A: 

The best way really depends on the function and the arguments. Each of your options is a good idea in different situations. I generally try these in the following order until one of them works:

  1. Using optional arguments like y = y || 'default'. This is convenient if you can do it, but it may not always work practically, e.g. when 0/null/undefined would be a valid argument.

  2. Using number of arguments. Similar to the last option but may work when #1 doesn't work.

  3. Checking types of arguments. This can work in some cases where the number of arguments is the same. If you can't reliably determine the types, you may need to use different names.

  4. Using different names in the first place. You may need to do this if the other options won't work, aren't practical, or for consistency with other related functions.

Matthew Crumley
+8  A: 

The best way to do function overloading with parameters is not checking the arguments length and checking the types. Checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

What most developers do is they tag on a object as the last argument to their methods. The object can hold any thing.

function foo(a,b,opts){

}


foo(1,2,{"method":"add"};
foo(3,4,{"test":"equals", "bar":"tree"}

Than you can handle it anyway you want in your method. [Switch, if-else, etc.]

epascarello
A: 

You can do the following:

Function test(x,y,z) {
 alert(x+y+z);
}
Function test(x,y) {
 test(x,y,3);
}
Function test(x) {
 test(x,2,3);
}
Function test() {
 test(1,2,3);
}
Ryan