ActionScript Rest Parameters

Word Count: 208

The more and more I write ActionScript the more I really enjoy it. Tonight I was working on an problem where I needed to pass x number of arguments to a function. Lucky for me I found out that ActionScript 3 supports rest parameters. The rest parameter specifies that a function will accept any number of comma delimited arguments. This is a quick class I whipped up to show an example of how you can take advantage of the cool little feature of the language.

Comments

#1 Posted By: Tink Posted On: 1/2/09 6:48 PM
One thinsg to watch out for is if you override a method, but then need to pass the parameters through to the super. If you pass 3 params through to the method, args will be an array of strings with the length of 3. If you pass that straight onto the super, args will be an array, that contains 1 single array.

// overriding method
override public function addColor( ...args ):void
{
var numItems:int = args.length;
trace( numItems:int ); // 3
super.addColor( args );
}

// overriden method
public function addColor(...args):void
{
var numItems:int = args.length;
trace( numItems:int ); // 1
for( var i:uint = 0; i < numItems:int; i++ )
{
trace( args[ i ] );
}
}

you can handle this buy using Function.apply().

// overriding method
override public function addColor( ...args ):void
{
var numItems:int = args.length;
trace( numItems:int ); // 3
super.addColor.apply( this, args );
}

// overriden method
public function addColor(...args):void
{
var numItems:int = args.length;
trace( numItems:int ); // 3
for( var i:uint = 0; i < numItems:int; i++ )
{
trace( args[ i ] );
}
}
#2 Posted By: Dan Vega Posted On: 1/2/09 6:55 PM |
Author Comment
Thanks for the tip!
#3 Posted By: Gareth Arch Posted On: 1/2/09 10:24 PM
Nice! I think I had read that somewhere, but hadn't really checked it out. The "apply()" method is definitely a useful tool to have.
#4 Posted By: ryan Posted On: 1/4/09 5:01 PM
yeah nice one... i'll make note of that...


Post Your Comment







Show Captcha

If you subscribe, any new posts to this thread will be sent to your email address.

Copyright © 2007 Dan Vega | BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.