Book HomeActionScript: The Definitive GuideSearch this book

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 Array object class, but it is up to us to create individual arrays.

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

new ConstructorFunction( )

Let's instantiate our first object using a constructor that's already built into ActionScript: the Object( ) constructor. The Object( ) constructor creates a completely generic object (hence its name), the foundation object type upon which all other object types are based. The following code creates a new generic object:

new Object( )

When we instantiate an object, we normally store the resulting instance in a variable, array element, or object property for later access. For example:

var myObject = new Object( );

Instantiating an object in this manner gives us an empty object with no properties and only two very general methods. Generic objects, hence, are of limited use -- the real power of objects comes with specialized object classes. Before we learn how to make our own classes, we'll see how to use object properties and methods with objects of existing classes.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.