12.2. Creating an Instance of a Class
Problem
You want to access the properties and methods of a class to achieve a particular goal, but those properties and methods are specific to a particular object (i.e., an instance of the class).
Solution
Create a instance of the class
using the new
operator and the constructor function for the class of interest. Then
access the properties and methods of the instance, as returned by the
constructor function.
Discussion
Many ActionScript classes must
be
instantiated before you can use them. This means
that you must create an object that is based on the blueprint defined
by the class. For example, the Array
class
defines the blueprint for all arrays. All arrays have the same kinds
of properties and methods; however, each array instance is an
individual object that merely inherits the
common properties and methods from the class. It is important that
each instance be individualized so that when you request the value
for arrayA.length
, you retrieve the length of
arrayA
and not the length of some other array,
such as arrayB
.
To create an instance of a class, you typically use the
new
operator with the appropriate
constructor function
for the
class. The constructor function takes
the same name as the class itself and is followed by the function
operator (that is, parentheses). For example, the following creates a
new generic instance of the Object
class:
myObject = new Object( );
Note that the new
statement returns an instance of the class, which ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.