Dynamic Parameters in ActionScript 3.0

Note: 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:

//function to convert Fahrenheit to Celsius

private function toCelsius(_Fahrenheit:Object, …rest):Number{

var _Celsius:Number = (5/9)*(_Fahrenheit.degrees-32);
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:

//you can name your optional parameter and reference it accordingly

private function overloadTest(…myArguments):String{

switch (myArguments.length){

case 0:

… code A …
return “signature A”;

case 1:

… code B …
return “signature B”;

case 2:

… code C …
return “signature C”;

default:

… code D …
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: , ,

2 Responses to “Dynamic Parameters in ActionScript 3.0”

  1. Cimiamaxy Says:

    Your site displays incorrectly in Opera, but content excellent! Thank you for your wise words:)

  2. Kalen Gibbons Says:

    Hello Cimiamaxy,
    Thank you for your feedback. I just switched blogging platforms two days ago and am still working out all the bugs. So thanks for the heads-up. However, I’m running Opera 9.63 and don’t see any problems, so any additional information you could provide would be really helpful. Like what version of Opera and what issues you’re seeing.

    Thanks again,
    Kalen Gibbons

Leave a Reply