Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Classes > Example: Writing custom classes > Writing the constructor function | |||
You have already learned how to write the class declaration in Creating and packaging your class files. In this part of the chapter, you write what's called the class file's constructor function.
|
NOTE |
|
You learn how to write the comments, statements, and declarations in later sections. |
Constructors are functions that you use to initialize (define) the properties and methods of a class. By definition, constructors are functions within a class definition that have the same name as the class. For example, the following code defines a Person class and implements a constructor function. In OOP, the constructor function initializes each new instance of a class.
A class's constructor is a special function that is called automatically when you create an instance of a class using the new operator. The constructor function has the same name as the class that contains it. For example, the Person class you created contained the following constructor function:
// Person class constructor function
public function Person (uname:String, age:Number) {
this.__name = uname;
this.__age = age;
}
Consider the following points when you write constructor functions:
The term constructor is also typically used when you create (instantiate) an object based on a particular class. The following statements are calls to the constructor functions for the top-level Array class and the custom Person class:
var day_array:Array = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var somePerson:Person = new Person("Tom", 30);
Next you'll add a special function called a constructor function.
|
NOTE |
|
The following exercise is part of Example: Writing custom classes. If you do not wish to progress through the example, you can download the class files from www.helpexamples.com/flash/learnas/classes/. |
class com.adobe.utils.ClassA {
function ClassA() {
trace("ClassA constructor");
}
}
The previous code defines a constructor method for the ClassA class. This constructor traces a simple string to the Output panel, which will let you know when a new instance of the class has been created.
class com.adobe.utils.ClassB {
function ClassB() {
trace("ClassB constructor");
}
}
To continue writing your class file, see Adding methods and properties.
Flash CS3
Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flash/9.0/main/00000791.html