Using class members: a simple example

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's incremented 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 is incremented by 1 and the current value of widgetCount is displayed in the Output panel.

To create an instance counter using a class variable:

  1. Create a new ActionScript (AS) file.
  2. Add the following code to the file:
    class Widget {
      static var widgetCount:Number = 0; // initialize class variable
      function Widget() {
        trace("Creating widget #" + widgetCount);
        widgetCount++;
      }
    }
    

    The widgetCount variable is declared as static, and so initializes to 0 only once. Each time the Widget class's constructor function is called, it adds 1 to widgetCount, and then displays the number of the current instance that's being created.

  3. Save your file as Widget.as.
  4. Create a new Flash (FLA) document and save it as createWidget.fla in the same directory as Widget.as.

    In this file, you'll create new instances of the Widget class.

  5. In createWidget.fla, select Layer 1 in the Timeline and open the Actions panel (Window > Development Panels > Actions).
  6. Add the following code to the Actions panel.
    // Before you create any instances of the class, 
    // widgetCount is zero (0)
    trace("Widget count at start: " + Widget.widgetCount);
    var widget_1 = new Widget();
    var widget_2 = new Widget();
    var widget_3 = new Widget();
    
  7. Save the file, and then test it (Control > Test Movie).

    You should see the following in the Output panel:

    Widget count at start: 0
    Creating widget # 0
    Creating widget # 1
    Creating widget # 2