114 Chapter 6: Using the Built-In Classes
About classes and instances
In object-oriented programming, a class defines a category of object. A class describes the
properties (data) and behavior (methods) for an object, much like an architectural blueprint
describes the characteristics of a building. To use the properties and methods defined by a class,
you must first create an instance of that class. The relationship between an instance and its class is
similar to the relationship between a house and its architectural blueprints.
Creating a new object
To create an instance of an ActionScript class, use the
new operator to invoke the class’s
constructor function. The constructor function always has the same name as the class, and returns
an instance of the class, which you typically assign to a variable.
For example, the following code creates a new Sound object.
var song:Sound= new Sound();
In some cases, you don’t need to create an instance of a class to use it. For more information, see
“About class (static) members” on page 114.
Accessing object properties
Use the dot (
.) operator to access the value of a property in an object. Put the name of the object
on the left side of the dot, and put the name of the property on the right side. For example, in the
following statement,
myObject is the object and name is the property:
myObject.name
The following code creates a new TextField object, and then sets its autoSize property to true.
var my_text = new TextField();
my_text.autoSize = true;
You can also use the array access operator ([]) to access the properties of an object. See “Dot and
array access operators” on page 49.
Calling object methods
You call an object’s method by using the dot (
.) operator followed by the method. For example,
the following code creates a new Sound object and calls its
setVolume() method.
mySound = new Sound(this);
mySound.setVolume(50);
About class (static) members
Some built-in ActionScript classes have what are called class members (or static members). Class
members (properties and methods) are accessed or invoked not on an instance of the class but on
the class name itself. That is, you don’t create an instance of the class in order to use those
properties and methods.
For example, all of the properties of the Math class are static. The following code invokes the
max() method of the Math class to determine the larger of two numbers.
var largerNumber = Math.max(10, 20);