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.

To create an instance counter using a class variable:

  1. Select File > New and then select ActionScript File, and then click OK.
  2. Type the following code into the Script window:
    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.

  3. Save your file as Widget.as.
  4. Select File > New and then select Flash Document to create a new FLA, and save it as widget_test.fla in the same directory as Widget.as.
  5. In widget_test.fla, type the following code into Frame 1 of the Timeline:
    // 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 
    
  6. Save the changes to widget_test.fla.
  7. Select Control > Test Movie to test the file.

    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