O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Functions to Create Objects

As we've seen throughout this book, most objects in ActionScript are created using classes. However, it is also possible to create objects using standalone function closures. The following code shows the basic approach. It uses an example function, Employee( ), to create an object:

// Create the function
function Employee () {
}

// Use the function to create an object, and assign that
// object to the variable, worker
var worker = new Employee();

Notice that the variable worker is untyped. From a datatype perspective, the object referenced by worker is an instance of the Object class. There is no Employee class, so there is no Employee datatype. The following code, therefore, causes an error (because the Employee datatype does not exist):

// ERROR!
var worker:Employee = new Employee();

A function closure used to create an object is referred to as a constructor function (not to be confused with a constructor method, which is part of a class definition). In ActionScript 3.0, standalone functions declared at the package-level or in frame scripts cannot be used as constructor functions. Hence, the preceding code would be legal within a method or a function, or outside of a package statement only. To create a constructor function that is legal in a frame script in the Flash authoring tool, define an anonymous function and assign it to a variable, as shown in the following code:

var Employee:Function = function () {
};

For the sake of code clarity, the remainder ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required