Dynamic Parameters in ActionScript 3.0
Posted in ActionScript, Flex on July 18th, 2007 by Kalen GibbonsNote: This post has been renamed, because its original title “Optional Parameters in ActionScript 3.0″ was a bit misleading. For more information on optional parameters please visit the following livedocs page.
You’ve gotta love …rest! Since ActionScript 3.0 doesn’t support overloaded constructors (booo), …rest is a pseudo way of overloading your methods. …rest is an argument parameter that allows you to pass in multiple arguments of various lengths and datatypes. So, for example, if you have a function that converts degrees Fahrenheit into degrees Celsius, you may need to call this function with various parameters:
private function toCelsius(_Fahrenheit:Object, …rest):Number{
return _Celsius
}
//passes single parameter, Fahrenheit object
Alert.show(“Degress Celcius: “ + toCelsius(degreeFahrenheit));
//passes two parameters, Fahrenheit object and length
degFarenheit = new DataGridColumn();
degFarenheit.labelFunction = toCelsius as Function;
By using …rest, the toCelsius function will ignore any additional parameters that might get passed in and that would normal throw an error. What’s even better, is that you can name your …(rest) parameter and ActionScript will store a reference to all the parameters passed in as an array. This is what really allows you to create one method signature that can act like overloaded functions. For example:
private function overloadTest(…myArguments):String{
return “signature A”;
case 1:
return “signature B”;
case 2:
return “signature C”;
default:
return “signature D”;
}
}
And although this doesn’t make up for ActionScript’s lack of overloading support, it does make life a little simpler and more flexible. I am a big fan of …rest!
Tags: arguments, overloaded, parameters