User Guide
252 Chapter 10: Creating Custom Classes with ActionScript 2.0
6.
To create the properties for the Person class, use the var keyword to define two variables named
age and name, as shown in the following example:
class Person {
var age:Number;
var name:String;
}
Tip: By convention, class properties are defined at the top of the class body, which makes the
code easier to understand, but this isn’t required.
The colon syntax (var age:Number and var name:String) used in the variable declarations
is an example of strict data typing. When you type a variable in this way (
var
variableName:variableType
), the ActionScript 2.0 compiler ensures that any values
assigned to that variable match the specified type. If the correct data type is not used in the
FLA file importing this class, an error is thrown by the compiler. Using strict typing is good
practice and can make debugging your scripts easier. (For more information, see “Strict data
typing” on page 41.)
7.
Next, you’ll add a special function called a constructor function. In object-oriented
programming, the constructor function initializes each new instance of a class.
The constructor function always has the same name as the class. To create the class’s
constructor function, add 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;
}
}
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 255.
If you don’t create a constructor function, an empty one is created automatically
during compilation.
8.
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;