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
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 class's constructor function, passing as parameters the values
and 32.
The
newPerson
compiler to ensure that you don't try to access properties or methods that aren't defined in the
class. (The exception is if you declare the class to be dynamic using the
"Creating dynamic classes" on page
To create an instance of the Person class in a Flash document:
In Flash, select File > New, select Flash Document from the list of document types, and
1
click OK.
Save the file as createPerson.fla in the PersonFiles directory you created previously.
2
Select Layer 1 in the Timeline and open the Actions panel (Window > Development
3
Panels > Actions).
In the Actions panel, enter the following code:
4
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,
calls the
showInfo()
Save your work, then select Control > Test Movie. You should see the following in the
5
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
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.
160
Chapter 9: Creating Classes with ActionScript 2.0
operator, just as you would when creating an instance of a built-in
new
.
variable is typed as a Person object. Typing your objects in this way enables the
173.)
method on each instance.
person_1
169).
"Nate"
keyword. See
dynamic
and
, and then
person_2
Need help?
Do you have a question about the FLASH MX 2004 - ACTIONSCRIPT and is the answer not in the manual?