Actionscript 3 Designer Toolkit

More design, less programming

Actionscript 3 Designer Toolkit header image 2

Using Actionscript 3 …(rest) to pass optional parameters

January 5th, 2010 · 2 Comments · Tutorials

This post examines several methods for passing optional parameters to functions and class constructors.  Using …rest allows an arbitrary number of parameters to be passed to the function. The list of comma delimited arguments (often called the rest parameter) is treated as an array by the function.

In the example below, the function is coded to receive an arbitrary set of parameters and treats them as an array named args.

function getParameters( ...args ):void
{
        // process args as array
	for ( var i:uint=0; i<args.length; i++ )
	{
		trace( 'parameter: ' + args[i] );
	}
}
 
getParameters( 'news', true, 14, 1.717 );

In this next example, two required parameters and an arbitrary number of optional parameters are accepted by the function.

function getParameters( newSource:String, newsSection:uint, ...others ):void
{
	trace( 'News source: ' + newSource );
        trace( 'News section: ' + newsSection );
 
	for ( var i:uint=0; i<others.length; i++ )
	{
		trace( 'Optional: ' + others[i] );
	}
}
 
getParameters( 'New York Times', 6, false, 3, 14 );

A final example passes an array as the optional parameter.  In order to process the array properly, the apply method is used as shown below.

function getParameters( ...args ):void
{
	for ( var i:uint=0; i<args.length; i++ )
	{
		trace( 'optional: ' + args[i] );
	}
}
 
var args:Array = [ 'northeast', false, 0, 3.14 ];
 
getParameters.apply( this, args );

Caveat: Since the number of arguments and their types are not validated, it is left to the coder to to do all type checking within the function.

Post to Twitter

Tags: ···

2 Comments so far ↓

Leave a Comment

Spam Protection by WP-SpamFree