Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Classes > About working with custom classes in an application > About class members > Using class members | |||
One use of class (static) members is to maintain state information about a class and its instances. For example, suppose you want to keep track of the number of instances that have been created from a particular class. An easy way to do this is to use a class property that increments each time a new instance is created.
In the following example, you'll create a class called Widget that defines a single, static instance counter named widgetCount. Each time a new instance of the class is created, the value of widgetCount increments by 1 and the current value of widgetCount is displayed in the Output panel.
class Widget {
//Initialize the class variable
public static var widgetCount:Number = 0;
public function Widget() {
Widget.widgetCount++;
trace("Creating widget #" + Widget.widgetCount);
}
}
The widgetCount variable is declared as static, so it initializes to 0 only once. Each time the Widget class's constructor statement is called, it adds 1 to widgetCount and then shows the number of the current instance that's being created.
// Before you create any instances of the class,
// Widget.widgetCount is zero (0).
trace("Widget count at start: " + Widget.widgetCount); // 0
var widget1:Widget = new Widget(); // 1
var widget2:Widget = new Widget(); // 2
var widget3:Widget = new Widget(); // 3
trace("Widget count at end: " + Widget.widgetCount); // 3
Flash displays the following information in the Output panel:
Widget count at start: 0 Creating widget # 1 Creating widget # 2 Creating widget # 3 Widget count at end: 3
Flash CS3
Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flash/9.0/main/00000782.html