12.5. Creating a Custom Class

Problem

You want to create a custom ActionScript class to implement custom functionality or encapsulate related properties.

Solution

Create a constructor function and then assign properties and methods to its prototype.

Discussion

You might want to implement a custom class to encapsulate a series of methods and properties with related functionality. For example, you might implement a custom class that communicates with an external application. To create a custom class, first define a constructor function. The constructor function is defined in the typical fashion—either as a named function or as an anonymous function assigned to a variable. The latter technique is useful for creating globally accessible classes. Classes defined with named functions are accessible only within the scope of the timeline in which they are defined or by using the fully qualified target path.

Here are two degenerate examples. Obviously, constructor functions do not need to be empty; they can take parameters and they can have function bodies.

// Create a local class named MyClass.
function MyClass (  ) {}

// Create a global class named MyClass.
_global.MyClass = function (  ) {};

By convention, class names are capitalized. ActionScript is case-insensitive, so it is not technically an issue, but following this naming convention helps you easily distinguish classes from objects (instances of a class). Furthermore, the ECMA-262 standard, on which JavaScript is based, demands case-sensitivity. ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.