222 Functions and Methods
About nested functions
You can call a function from inside another function. This lets you nest functions so that you
can have them perform specific tasks in Flash.
For example, you can nest functions on a timeline to perform specific tasks on a string. Type
the following code on Frame 1 of the Timeline:
var myStr:String = "My marshmallow chicken is yellow.";
trace("Original string: " + myStr);
function formatText():Void {
changeString("Put chicken in microwave.");
trace("Changed string: " + myStr);
}
function changeString(newtext:String):Void {
myStr = newtext;
}
// Call the function.
formatText();
Select Control > Test Movie to test the nested function. The formatText() and
changeString() functions are both applied to the string when you call the formatText()
function.
Understanding methods
Methods are functions that are associated with a class. The class could be a custom class or
built-in classes that are part of the ActionScript language. For information on comparing
methods to functions, see “About functions and methods” on page 201 and “About types of
methods and functions” on page 203.
For example,
sortOn() is a built-in method associated with the Array class (sortOn is a
function of the predefined Array class built into Flash).
To use the sortOn() method in a FLA file:
1. Create a new Flash document and save it as methods.fla.
2. Add the following code to Frame 1 of the Timeline:
var userArr:Array = new Array();
userArr.push({firstname:"George", age:39});
userArr.push({firstname:"Dan", age:43});
userArr.push({firstname:"Socks", age:2});
userArr.sortOn("firstname");
var userArrayLenth:Number = userArr.length;
var i:Number;
for (i = 0; i < userArrayLenth; i++) {
trace(userArr[i].firstname);
}