Entry
Function calling another function: How can Fun1 pass its arguments to Fun2? Fun2(arguments) fails.
Dec 1st, 2002 15:04
Mark Filipak,
Well, this was somewhat answered in this JavaScripts FAQTS question:
"How can two functions (created as properties of a customs object) share
information between them ?" But given its title, I didn't look at it.
The following *does not work*:
//_____ IN Fun1, THE FOLLOWING DO NOT WORK!
Fun2(arguments); // DOES NOT WORK.
Fun2(Fun1.arguments); // DOES NOT WORK.
Instead, to pass all of Fun1's arguments to Fun2, where the number of
arguments at the time when Fun1 is called is unknown, do this:
//_____ IN Fun1, THE FOLLOWING DOES WORK!
Fun2.apply(this, arguments);
As you see, Fun2's .apply() method is used -- all functions have an
unenumerated .apply method -- plus an extra parameter, 'this', is also
passed as the first argument to Fun2's .apply() method. Passing 'this'
(without the quotes of course, so that the Fun1 object is passed instead
of a string) sets the context of the arguments so that Fun2 can get at
them. The Fun2.apply() method provides the internal mechanism to get the
arguments into the body of Fun2 -- it is the .apply() method that uses
'this' to accomplish the magic.