## Tuesday, October 5, 2010

### Function Arguments in Depth

Function which takes infinite arguments
`function infiniteArgs(...args):void {    trace( args );}infiniteArgs( 1, 2 );infiniteArgs( 1, 2, 3, 4, 5 );infiniteArgs( 1, 2, 3, 4, 5, 6, 7 );infiniteArgs( 'a', 'b', 'c' );`
Another method without all this hassle is to do like the below. I recommend this instead of the above method:
`var inf:Function = function():void {    trace(arguments);}inf( 1, 2, 3, 4 );inf( 'a', 'b' );`
Arguments array
`function foo( a:int, b:int, c:int ):void {    trace( arguments );    //displays the arguments passed}foo( 1, 2, 3 );foo( 0, 10, 110 );`
It will display the arguments passed into the function.
Now you can use arguments.length, arguments[0] etc.
`function foo( a:int, b:int, c:int ):void {    trace( "args: " + arguments );    trace( "len: " + arguments.length );    trace( "arguments[2]: " + arguments[2] );}foo( 1, 2, 3 );foo( 1, 10, 110 );`
When using mutliple parameters the arguments are referred by the variable that you put after the 3 dots. i.e:
`function foo(...myCoolArgs):void {    //instead of myCoolArgs if you gave arguments you'll get undefined error.    trace( "args: " + myCoolArgs );    trace( "len: " + myCoolArgs.length );}`
Passing arguments to another function
You have a function which received arguments. You need to send those arguments to another function as arguments itself instead of an array. For that you can use the 'apply' function.
`//normal situationfunction fooA(...myCoolArgs):void {    trace( "args: " + myCoolArgs );    trace( "len: " + myCoolArgs.length );    //you get 5    fooB( myCoolArgs );}function fooB(...args):void {    trace( "args: " + args );     trace( "len: " + args.length );    // you get 1 instead of 5}fooA( 0, 1, 2, 3, 4 );`
Its passed as an argument array. So what you do is:
`function fooA(...myCoolArgs):void {    trace( "args: " + myCoolArgs );    trace( "len: " + myCoolArgs.length );    //you get 5    fooB.apply( this, myCoolArgs );    //pass it like this}function fooB(...args):void {    trace( "args: " + args );     trace( "len: " + args.length );    // now you get 5}fooA( 0, 1, 2, 3, 4 );`
More cooler version:
`var fooA:Function = function():void {    trace( "args: " + arguments );    trace( "len: " +  arguments.length );    fooB.apply( this, arguments );}var fooB:Function = function():void {    trace( "args: " + arguments );     trace( "len: " + arguments.length );}fooA( 0, 1, 2, 3, 4 );fooA( 'a', 'b', 'c' );`