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
is incremented by 1 and the current value of
widgetCount
Output panel.
To create an instance counter using a class variable:
Create a new ActionScript (AS) file.
1
Add the following code to the file:
2
class Widget {
static var widgetCount:Number = 0; // initialize class variable
function Widget() {
trace("Creating widget #" + widgetCount);
widgetCount++;
}
}
The
widgetCount
Widget class's constructor function is called, it adds 1 to
number of the current instance that's being created.
Save your file as Widget.as.
3
Create a new Flash (FLA) document and save it as createWidget.fla in the same directory as
4
Widget.as.
In this file, you'll create new instances of the Widget class.
In createWidget.fla, select Layer 1 in the Timeline and open the Actions panel (Window >
5
Development Panels > Actions).
Add the following code to the Actions panel.
6
// 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();
Save the file, and then test it (Control > Test Movie).
7
You should see the following in the Output panel:
Widget count at start: 0
Creating widget # 0
Creating widget # 1
Creating widget # 2
166
Chapter 9: Creating Classes with ActionScript 2.0
. Each time a new instance of the class is created, the value of
variable is declared as static, and so initializes to 0 only once. Each time the
is displayed in the
widgetCount
, and then displays the
widgetCount
Need help?
Do you have a question about the FLASH MX 2004 - ACTIONSCRIPT and is the answer not in the manual?