Object-oriented ActionScript - Object Creation and Usage
(Page 3 of 7 )
Objects are created (instantiated) with the new operator, as in:
new ClassName()
where ClassName is the name of the class from which the object will be created.
For example, when we want to create a new SpaceShip object in our hypothetical game, we use this code:
new SpaceShip()
Note: The syntax for creating objects (e.g., new SpaceShip( )) is the same in ActionScript 2.0 as it was in ActionScript 1.0. However, the syntax for defining classes in ActionScript 2.0 differs from ActionScript 1.0.
Most objects are stored somewhere after they’re created so that they can be used later in the program. For example, we might store a SpaceShip instance in a variable named ship, like this:
var ship:SpaceShip = new SpaceShip();
Each object is a discrete data value that can be stored in a variable, an array element, or even a property of another object. For example, if you create 20 alien spaceships, you would ordinarily store references to the 20 SpaceShip objects in a single array. This allows you to easily manipulate multiple objects by cycling through the array and, say, invoking a method of the SpaceShip class on each object.
Object Usage An object’s methods provide its capabilities (i.e., behaviors)—things like “fire missile,” “move,” and “scroll down.” An object’s properties store its data, which describes its state at any given point in time. For example, at a particular point in a game, our ship’s current state might be speed is 300, damage is 14.
Methods and properties that are defined as public by an object’s class can be accessed from anywhere in a program. By contrast, methods and properties defined as private can be used only within the source code of the class or its subclasses. As we’ll learn in Chapter 4, methods and properties should be defined as public only if they must be accessed externally.
To invoke a method, we use the dot operator (i.e., a period) and the function call operator (i.e., parentheses). For example:
// Invoke the ship object's fireMissile( ) method.
ship.fireMissile();
To set a property, we use the dot operator and an equals sign. For example:
// Set the ship's speed property to 120.
ship.speed = 120;
To retrieve a property’s value, we use the dot operator on its own. For example:
// Display the value of the speed property in the Output panel.
trace(ship.speed);
 | If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!
Visit the O'Reilly Network http://www.oreillynet.com for more online content. |
Next: Encapsulation and Datatypes >>
More Flash Articles
More By O'Reilly Media