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/.

To add the constructor functions to your class files:

  1. Open the ClassA.as class file in the Flash authoring tool.
  2. Modify the existing class file so it matches the following code (the changes to make appear in boldface):
    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.

  3. Open the ClassB.as class file in the Flash authoring tool.
  4. Modify the class file so it matches the following code (the changes to make appear in boldface):
    class com.adobe.utils.ClassB {
        function ClassB() {
            trace("ClassB constructor");
        }
    }
    
  5. Save both ActionScript files before you proceed.

To continue writing your class file, see Adding methods and properties.


Flash CS3