User Guide

Using classes: a simple example 253
// Constructor function
function Person (myName:String, myAge:Number) {
this.name = myName;
this.age = myAge;
}
// Method to return property values
function getInfo():String {
return("Hello, my name is " + this.name + " and I’m " + this.age + "
years old.");
}
}
This code is the completed code for this class. The return value of the getInfo() function is
strictly typed (optional, but recommended) as a string.
9.
Save the file.
If youre using Flash MX 2004 (not Flash Professional), proceed to “Creating an instance of the
Person class” on page 253.
10.
(Optional, Flash Professional only) Check the syntax of the class file by selecting Tools > Check
Syntax, or pressing Control+T (Windows) or Command+T (Macintosh).
If any errors are reported in the Output panel, compare the code in your script to the final
code. If you cant fix the code errors, copy the completed code.
Youve successfully created a class file. To continued with this example, see “Creating an instance
of the Person class” on page 253.
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, the same as you would when creating an instance of a
built-in ActionScript class (such as the Date or Error class). You refer to the class using its fully
qualified class name or import the class; see “Importing classes” on page 271.
Continuing the example you started in “Creating a class file” on page 251, if you create a FLA file
in the same directory as the class file you created, you can refer to the class file using the fully
qualified class name, which is
Person. 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 "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. See “Strict data typing” on page 41. (The exception is if you declare the class to be dynamic
using the
dynamic keyword. See “Creating dynamic classes” on page 259.)