Using classes: a simple example 159
6 Next you’ll create the showInfo() method, which returns a preformatted string containing the
values of the
age and name properties. Add the showInfo() function definition to the class
body, as shown below.
class Person {
var age:Number;
var name:String;
// Method to return property values
function showInfo():String {
return("Hello, my name is " + name + " and I’m " + age + " years old.");
}
}
Notice the use of data typing (optional but recommended) in the function definition.
function showInfo():String {...}
In this case, what’s being typed is the showInfo() function’s return value (a string).
7 The last bit of code you’ll add in this section is a special function called a constructor function.
In object-oriented programming, the constructor function initializes each new instance of
aclass.
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;
// Method to return property values
function showInfo():String {
return("Hello, my name is " + name + " and I’m " + age + " years old.");
}
// Constructor function
function Person (myName:String, myAge:Number) {
name = myName;
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. For more information about constructor functions,
see “Constructor functions” on page 163.
Note: If you don’t create a constructor function, an empty one is created automatically
during compilation.
8 Save the file as Person.as in the PersonFiles directory that you created in step 1.
If you’re using Flash MX 2004 (not Flash Professional), proceed to the next section.
9 (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 in step 7, above. If you can’t fix the code errors, copy the completed code in step 7 from
the Help panel.