Understanding methods 223
You use the sortOn() method of the Array class to create a new Array object named
userArr. The array is populated by three objects that contain a first name and age, and
then the array is sorted based on the value of each object’s
firstname property. Finally,
you loop over each item in the array and display the first name in the Output panel and
sort the names alphabetically by first letter.
3. Select Control > Test Movie to test the SWF file.
This code displays the following in the Output panel:
Dan
George
Socks
As demonstrated in “Writing named functions” on page 207, when you write the following
code on Frame 1 of the Timeline, your ActionScript code defines a function called
eatCabbage().
function eatCabbage() {
trace("tastes bad");
}
eatCabbage();
However, if you write the eatCabbage() function within a class file and, for example, call
eatCabbage() in the FLA file, then eatCabbage() is considered to be a method.
The next examples show you how to create methods within a class.
To compare methods and functions:
1. Create a new ActionScript file, select File > Save As, and save it as EatingHabits.as.
2. Type the following ActionScript code in the Script window:
class EatingHabits {
public function eatCabbage():Void {
trace("tastes bad");
}
}
3.
Save your changes to EatingHabits.as.
4. Create a new Flash document, select File > Save As, name it methodTest.fla, and save this
file in the same directory as EatingHabits.as.
5. Type the following ActionScript code onto Frame 1 of the Timeline:
var myHabits:EatingHabits = new EatingHabits();
myHabits.eatCabbage();