In your text editor, enter the following code (in this procedure, new code you type in each step
4.
is
):
bold
class Person {
}
This is called the class declaration. In its most basic form, a class declaration consists of the
keyword, followed by the class name (Person, in this case), and then left and right curly
class
braces (
). Everything between the braces is called the class body and is where the class's
{}
properties and methods are defined.
The name of the class (Person) must exactly match the name of the AS file that contains it
(Person.as). This is very important; if these two names don't match exactly, including
capitalization, the class won't compile.
To create the properties for the Person class, use the
5.
and
, as shown in the following example:
age
name
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
is an example of strict data typing. When you type a variable in this way (
variableName:variableType
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
typing" on page
24.)
Next, you'll add a special function called a constructor function. In object-oriented
6.
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;
}
}
var
and
var name:String
), the ActionScript 2.0 compiler ensures that any values
keyword to define two variables named
) used in the variable declarations
var
Using classes: a simple example
"Strict data
49
Need help?
Do you have a question about the FLEX-FLEX ACTIONSCRIPT LANGUAGE and is the answer not in the manual?