Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Functions and Methods > 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 and About types of methods and functions.
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).
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);
}
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.
This code displays the following in the Output panel:
Dan George Socks
As demonstrated in Writing named functions, 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.
class EatingHabits {
public function eatCabbage():Void {
trace("tastes bad");
}
}
var myHabits:EatingHabits = new EatingHabits(); myHabits.eatCabbage();
When you use this ActionScript, you are calling the eatCabbage() method of the EatingHabits class.
|
NOTE |
|
When you use methods of any built-in class (in addition to the custom class you wrote earlier in this procedure), you are using a method on a timeline. |
function eatCarrots():Void {
trace("tastes good");
}
eatCarrots();
In this code, you write and call the eatCarrots() function.
Flash CS3