Functions in ActionScript
Functions are central in ActionScript. We’ll learn about functions with a few different examples.
package {
import flash.display.Sprite;
import flash.text.TextField;
public class Functions extends Sprite {
public function Functions() {
// Here's a function that takes two Numbers and returns
// their sum as a Number.
function plus(a:Number, b:Number):Number {
// ActionScript doesn't require explicit returns,
// but it's good practice to include them.
return a + b;
}
// In ActionScript, we can't omit type declarations
// for parameters, even if they're the same type.
function plusPlus(a:Number, b:Number, c:Number):Number {
return a + b + c;
}
// Call a function just as you'd expect, with
// name(args).
var res:Number = plus(1, 2);
trace("1+2 = " + res);
res = plusPlus(1, 2, 3);
trace("1+2+3 = " + res);
}
}
}
To run this ActionScript code, you would typically compile it into a SWF file and then run it in a Flash Player or AIR runtime environment. The output would be:
1+2 = 3
1+2+3 = 6
There are several other features to ActionScript functions. One is the ability to use rest parameters and default parameter values, which we’ll look at next.
Note: ActionScript uses trace()
for console output, which is similar to println()
in other languages. In a real application, you might use a TextField to display output on the screen.
Also, ActionScript requires all code to be inside a class, unlike Go where you can have top-level functions. The Functions
class extends Sprite
, which is a basic display object in the Flash framework.