EasyManua.ls Logo

MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT - Page 160

MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT
816 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
160 Chapter 9: Creating Classes with ActionScript 2.0
Creating an instance of the Person class
The next step is to create an instance of the Person class in another script, such as a frame script in
a Flash (FLA) document or another AS script, and assign it to a variable. To create an instance of
a custom class, you use the
new operator, just as you would when creating an instance of a built-in
ActionScript class (such as the XML or TextField class).
For example, the following code creates an instance of the Person class and assigns it to the
variable
newPerson.
var newPerson:Person = new Person("Nate", 32);
This code invokes the Person classs constructor function, passing as parameters the values "Nate"
and 32.
The
newPerson variable is typed as a Person object. Typing your objects in this way enables the
compiler to ensure that you dont try to access properties or methods that arent defined in the
class. (The exception is if you declare the class to be dynamic using the
dynamic keyword. See
“Creating dynamic classes” on page 173.)
To create an instance of the Person class in a Flash document:
1 In Flash, select File > New, select Flash Document from the list of document types, and
click OK.
2 Save the file as createPerson.fla in the PersonFiles directory you created previously.
3 Select Layer 1 in the Timeline and open the Actions panel (Window > Development
Panels > Actions).
4 In the Actions panel, enter the following code:
var person_1:Person = new Person("Nate", 32);
var person_2:Person = new Person("Jane", 28);
trace(person_1.showInfo());
trace(person_2.showInfo());
The above code creates two instances of the Person class, person_1 and person_2, and then
calls the
showInfo() method on each instance.
5 Save your work, then select Control > Test Movie. You should see the following in the
Output panel:
Hello, my name is Nate and I'm 32 years old.
Hello, my name is Jane and I'm 28 years old.
When you create an instance of a class by calling its constructor function, Flash looks for an
ActionScript file of the same name as the constructor in a set of predetermined directory
locations. This group of directory locations is known collectively as the classpath (see
“Understanding the classpath” on page 169).
You should now have an overall idea of how to create and use classes in your Flash documents.
The rest of this chapter explores classes and interfaces in more detail.

Table of Contents

Related product manuals