The Singleton object can then be accessed using
This also means that the Singleton object is not created until it is actually needed—that is, until
some other code asks for it by calling the
creation and can help code efficiency in many circumstances.
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.
Add the following code to your script file:
4.
// 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();
Class members and subclasses
Class members propagate to subclasses of the superclass that defines those members. In the
previous example (see
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() {
62
Chapter 2: Creating Custom Classes with ActionScript 2.0
getInstance
. Each time a new instance of the class is created, the value of
variable is declared as static, so it initializes to 0 only once. Each time the
"Using class members: a simple example" on page
Singleton.getInstance();
method. This is typically called lazy
widgetCount
widgetCount
is displayed in the
and then shows the
62), you used a class
Need help?
Do you have a question about the FLEX-FLEX ACTIONSCRIPT LANGUAGE and is the answer not in the manual?