User Guide

50 Chapter 2: Creating Custom Classes with ActionScript 2.0
The Person() constructor function takes two parameters, myName and myAge, and assigns
those parameters to the
name and age properties. The two function parameters are strictly
typed as String and Number, respectively. Unlike other functions, the constructor function
should not declare its return type. For more information about constructor functions, see
“Constructor functions” on page 52.
If you dont create a constructor function, an empty one is created automatically
during compilation.
7.
Last, you’ll create the getInfo() method, which returns a preformatted string containing the
values of the
age and name properties. Add the getInfo() function definition to the class body,
after the constructor function, as shown in the following code:
class Person {
var age:Number;
var name:String;
// 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.
8.
Save the file.
Youve successfully created a class file. To continued with this example, see “Creating an instance
of the Person class” on page 50.
Creating an instance of the Person class
The next step is to create an instance of the Person class in another 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 65.
Continuing the example you started in “Creating a class file” on page 48, 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);