Table of Contents

12.2 Instantiating Objects

Although it may sound backward, let's assume that we have already created an object class. This assumption isn't too ludicrous, because ActionScript provides many built-in classes, and the custom classes we'll build will behave similarly. Assuming we have an object class, we have to create a specific object instance (i.e., a copy) based on the class. For example, ActionScript provides the TextField class, but it is up to us to create individual text fields.

To create an instance of an object (i.e., to instantiate the object), we normally use the new operator with a constructor function, which initializes the object. The general syntax is:

new ConstructorFunction( )

Let's instantiate our first object, using a constructor function that's already built into ActionScript: the Date( ) constructor. A Date object represents a particular point in time. When we instantiate a new object, we normally store the resulting instance in a variable, an array element, or a property of another object for later access. For example, the following code creates a new Date object and stores a reference to it in the variable named now:

var now = new Date( );

A specific time is a complex set of numbers that includes a second, minute, hour, day, month, and year. Using a Date object's methods, we can easily check or set any aspect of the time represented by the object. For example, we can invoke the getHours( ) method to check the hour (in 24-hour format), as follows:

trace("The current hour is: " + now.getHours( ));

Let's take a closer look at how to use an object's properties and methods before showing how to add them to our own custom classes.


Table of Contents