faqts : Computers : Programming : Languages : JavaScript : Language Core : prototypes/inheritance

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

8 of 9 people (89%) answered Yes
Recently 6 of 7 people (86%) answered Yes

Entry

How can I pass arguments to a function through to a second function?

May 20th, 2002 17:26
Daniel LaLiberte, Russ Thomas, Nathan Wallace,


In browsers that support JavaScript 1.2 (NN4 or IE4 and above), 
you can simply do:
function f1 () {
  f2.apply(this, arguments);
}
function f2 () {
  alert(arguments.length);
}
f1(1, 2, 3)
The use of 'this' would make more sense when used in a method,
of course.  You can use null instead otherwise.
Or if you have a propensity for pain and suffering, you could do
something like the following:
function f1 () {
  var s = 'f2 (';
  for (var i = 0; i < arguments.length; i++)
    s += 'arguments[' + i + ']' + ',';
  s = s.substring (0, s.length - 1);
  s += ')';
  eval(s);
}
function f2 () {
  alert(arguments.length);
}
f1(new Object(), 'a', 3)
--------------
While this method does not truly pass along the args, for JavaScript 1.0
(the 'caller' property was deprecated by ECMAScript) it's 
much shorter and appropriate in certain circumstances.
function f1()
{
  f2();
}
function f2()
{
  var args = f2.caller.arguments;
  alert(args.length);
  for(var i = 0;i < args.length; i++)
    alert(args[i]);
}
f1(1,2,3);