Entry
Can I have the same function twice with different number of arguments?
Can a function process a different number of arguments?
Mar 28th, 2000 13:34
Thor Larholm, Martin Honnen,
There is only one valid function definition possible but you can script
your function to receive a varying number of arguments. For instance
function functionName (arg0, arg1, arg2, arg3) {
arg0 = arg0 == void 0 ? 0 : arg0;
arg1 = arg1 == void 0 ? 0 arg1;
arg2 = arg2 == void 0 ? 0 arg2;
arg3 = arg3 == void 0 ? 0 arg3;
...
}
checks for each of the four defined formal parameters arg0 .. arg3
whether actually a value has been passed and if not assigns some
default value.
If you don't know the number of arguments at all you don't need to
define any formal parameters but you can use the
arguments
array to access the arguments dynamically e.g.
function functionName () {
for (var a = 0; a < arguments.length; a++)
alert(arguments[a]);
}
functionName (1, 2, 3);
functionName ('Kibology', 'JavaScript', 'FAQTs');
loops through the argument array and alerts every argument passed in.
You can also combine the two methods as in
function functionName (arg0, arg1) {
alert('arg0: ' + arg0);
alert('arg1: ' + arg1);
for (var a = 2; a < arguments.length; a++)
alert('additional argument: ' + arguments[a]);
}
functionName ('Kibo', 'Xibo', 'Kibology', 'Scriptology');