faqts : Computers : Programming : Languages : JavaScript : Language Core : Functions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

110 of 143 people (77%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Is it possible to do function overloading in Javascript?

Mar 21st, 2005 20:22
Arijit Sarbagna, Jean-Bernard Valentaten, JT Glass,


There is a way of doing it, although it is no real overloading.
JavaScript functions can have a multitude of arguments. In fact all 
arguments that are passed to a function are saved in an array called 
arguments[].
function showArgs()
{
  for (var i = 0; i < this.arguments.length; i++)
    document.write(i + '. Argument: ' + this.arguments[i] + '<br>');
}
HTH,
Jean
*****************************************
That was good example.
Let us also review another possibility.
function showArgs(){
  var arg_no=showArgs.arguments.length;
  switch (arg_no){
    case 0:
       alert("No Arguments.");
       break; 
    case 1:
       alert("1 Argument."); 
       break;
    default:
       alert("Multiple Arguments.");      
  }
}
Regards
Arijit Sarbagna
http://www.solutions2day.com