User Guide

266 Chapter 10: Creating Custom Classes with ActionScript 2.0
The widgetCount variable is declared as static, so it initializes to 0 only once. Each time the
Widget classs constructor function 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.
Create a new FLA document, and save it as createWidget.fla in the same directory as Widget.as.
In this file, youll 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:Widget = new Widget();
var widget_2:Widget = new Widget();
var widget_3:Widget = new Widget();
7.
Save your work, and then select Control > Test Movie. You should see the following text in the
Output panel:
Widget count at start: 0
Creating widget # 0
Creating widget # 1
Creating widget # 2
Class members and subclasses
Class members propagate to subclasses of the superclass that defines those members. In the
previous example (see “Using class members: a simple example” on page 265), you used a class
property to keep track of the number of instances of the class you created. You could create a
subclass of the Widget class, as shown in the following code:
class SubWidget extends Widget {
function SubWidget() {
trace("Creating subwidget # "+Widget.widgetCount);
}
}
The ActionScript 2.0 compiler can resolve static member references within class definitions. In
the previous example, if you don't specify the class name for the
Widget.widgetCount property,
but instead refer only to
widgetCount, the ActionScript 2.0 compiler ascertains that the reference
is actually to
Widget.widgetCount and correctly exports that property. Similarly, if you referred
to the property as
SubWidget.widgetCount, the compiler rewrites the reference (in the bytecode,
not in your AS file) as
Widget.widgetCount because SubWidget is a subclass of the Widget class.
However, for optimal readability of your code, it is recommended that you always use explicit
references in your code, as shown in the previous example, to easily identify where the definition
of a static member resides.