4.2 Constructor Functions (Take 1)

 <  Day Day Up  >  

Generally speaking, when we create an object, we also want to initialize it. For example, when we create an instance of our Box class, we might want to:

  • Initialize the new instance's size (i.e., set its width and height properties)

  • Represent the new instance on screen (i.e., call the draw( ) method)

To initialize and perform setup tasks for new objects of a class, we create a constructor function . The constructor function executes automatically each time an instance is created. Typically, when we create a class, we immediately add an empty constructor function to it. Then, as we develop the class, we add any necessary initialization code to the constructor function.

Let's now add an empty constructor function to our Box class. In the following code, lines 2 and 3 are the Box class's constructor function (or, more succinctly, "the Box constructor"):

 class Box {   public function Box ( ) {   } } 

Now that our Box class has an empty constructor function, we'll give the class some properties and methods. Once we add properties and methods , we can use them in the Box constructor to initialize Box instances.

However, we have a lot to learn about properties and methods in the upcoming sections before we can finish our Box constructor. Hence, we'll leave it empty for now and return to it later, under "Constructor Functions (Take 2)." For the sake of brevity, until we return to the Box constructor, we'll omit it from all intervening code samples. This omission is legal, if uncommon. When no constructor is provided for a class, ActionScript adds an empty one automatically at compile time.

 <  Day Day Up  >  


Essential ActionScript 2.0
Essential ActionScript 2.0
ISBN: 0596006527
EAN: 2147483647
Year: 2004
Pages: 177
Authors: Colin Moock

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net