BUY THIS BOOK
Add to Cart

PDF $31.99

Safari Books Online

What is this?

Looking to Reprint or License this content?


Essential ActionScript 2.0
Essential ActionScript 2.0

By Colin Moock
Book Price: $39.95 USD
£28.50 GBP
PDF Price: $31.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: ActionScript 2.0 Overview
Over the course of this book, we'll study ActionScript 2.0 and object-oriented programming in Flash exhaustively. There's lots to learn ahead but, before we get into too much detail, let's start with a quick summary of ActionScript 2.0's core features and Flash Player 7's new capabilities. If you have an ActionScript 1.0 background, the summary will give you a general sense of what's changed in the language. If, on the other hand, you're completely new to Flash or to ActionScript, you may want to skip directly to Chapter 2.
Introduced in Flash MX 2004 and Flash MX Professional 2004, ActionScript 2.0 is a major grammatical overhaul of ActionScript as it existed in Flash 5 and Flash MX (retroactively dubbed ActionScript 1.0). ActionScript 2.0 adds relatively little new runtime functionality to the language but radically improves object-oriented development in Flash by formalizing objected-oriented programming (OOP) syntax and methodology.
While ActionScript 1.0 could be used in an object-oriented way, it lacked a traditional, official vocabulary for creating classes and objects. ActionScript 2.0 adds syntactic support for traditional object-oriented features. For example, ActionScript 2.0 provides a class keyword for creating classes and an extends keyword for establishing inheritance. Those keywords were absent from ActionScript 1.0 (though it was still possible to create prototypical objects that could be used as classes). The traditional OOP syntax of ActionScript 2.0 makes the language quite familiar for programmers coming from other OOP languages such as Java and C++.
Most of the new OOP syntax in ActionScript 2.0 is based on the proposed ECMAScript 4 standard. Its specification is posted at http://www.mozilla.org/js/language/es4.
Here are some of the key features introduced in ActionScript 2.0. Don't worry if these features are new to you; the remainder of the book covers them in detail:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ActionScript 2.0 Features
Introduced in Flash MX 2004 and Flash MX Professional 2004, ActionScript 2.0 is a major grammatical overhaul of ActionScript as it existed in Flash 5 and Flash MX (retroactively dubbed ActionScript 1.0). ActionScript 2.0 adds relatively little new runtime functionality to the language but radically improves object-oriented development in Flash by formalizing objected-oriented programming (OOP) syntax and methodology.
While ActionScript 1.0 could be used in an object-oriented way, it lacked a traditional, official vocabulary for creating classes and objects. ActionScript 2.0 adds syntactic support for traditional object-oriented features. For example, ActionScript 2.0 provides a class keyword for creating classes and an extends keyword for establishing inheritance. Those keywords were absent from ActionScript 1.0 (though it was still possible to create prototypical objects that could be used as classes). The traditional OOP syntax of ActionScript 2.0 makes the language quite familiar for programmers coming from other OOP languages such as Java and C++.
Most of the new OOP syntax in ActionScript 2.0 is based on the proposed ECMAScript 4 standard. Its specification is posted at http://www.mozilla.org/js/language/es4.
Here are some of the key features introduced in ActionScript 2.0. Don't worry if these features are new to you; the remainder of the book covers them in detail:
  • The class statement, used to create formal classes. The class statement is covered in Chapter 4.
  • The extends keyword, used to establish inheritance. In ActionScript 1.0 inheritance was typically established using the prototype property but could also be established via the _ _proto_ _ property. Inheritance is covered in Chapter 6.
  • The interface statement, used to create Java-style interfaces (i.e., abstract datatypes). Classes provide implementations for interfaces using the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Features Introduced by Flash Player 7
In addition to the ActionScript 2.0 language enhancements, Flash Player 7 introduces some important new classes and capabilities. These are available only to Flash Player 7-format movies playing in Flash Player 7 or later. (For information on export formats, see "Setting a Movie's ActionScript Version and Player Version," later in this chapter.) Although these features are not the direct topic of study in this book, we'll cover a few of them during our exploration of ActionScript 2.0.
The key new features of Flash Player 7 include:
  • New array-sorting capabilities
  • The ContextMenu and ContextMenuItem classes for customizing the Flash Player context menu that appears when the user right-clicks (Windows) or Ctrl-clicks (Macintosh) on a Flash movie
  • Cross-domain policy files for permitting data and content to be loaded from an external domain
  • ID3 v2 tag support for loaded MP3 files
  • Mouse wheel support in text fields ( Windows only)
  • Improved MovieClip depth management methods
  • The MovieClipLoader class for loading movie clips and images
  • The PrintJob class for printing with greater control than was previously possible
  • Support for images in text fields, including flowing text around images
  • Improved text metrics (the ability to obtain more accurate measurements of the text in a text field than was possible in Flash Player 6)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Flash MX 2004 Version 2 Components
Flash MX introduced components—ready-to-use interface widgets and code modules that implement commonly needed functionality. Flash's built-in components make it relatively easy to create desktop-style Flash applications. Flash MX 2004 introduces the new v2 components, rewritten from scratch in ActionScript 2.0 and built atop version 2 of the Macromedia Component Architecture, which provides a much richer feature set than its predecessor. The new architecture necessitates new ways of developing and using components (see Chapter 12 for component usage). Officially, the v2 components require Flash Player 6.0.79.0 or higher; however, tests show that many v2 components work in earlier releases of Flash Player 6 (especially Flash Player 6.0.40.0 and higher). If you want to use a v2 component in a version prior to Flash Player 6.0.79.0, you should test your application extensively.
A single application produced in either Flash MX 2004 or Flash MX Professional 2004 can include both v2 components and Flash MX's v1 components, provided the v1 components have been updated to support ActionScript 2.0 and the movie is exported in ActionScript 2.0 format.
Don't confuse v1 and v2 components with the version of ActionScript in which they are written. Granted, v2 components are written in ActionScript 2.0 and there are no ActionScript 1.0 versions of the v2 components. However, although v1 components were written originally in ActionScript 1.0, versions updated to compile under ActionScript 2.0 are available.
The v1 component update for ActionScript 2.0 is available at the Flash Exchange (http://www.macromedia.com/exchange/flash), in the User Interface category, under the title "Flash MX Components for Flash MX 2004."
If nonupdated v1 components (i.e., those written in ActionScript 1.0) are used with v2 components in the same movie, some compile-time and runtime errors may occur, depending on the components used.
Do not mix ActionScript 1.0 OOP techniques with ActionScript 2.0 code. If you are using classes, inheritance, and other OOP features, make sure all your code is upgraded to ActionScript 2.0.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ActionScript 1.0 and 2.0 in Flash Player 6 and 7
ActionScript 1.0 is based on the ECMAScript 3 standard (as is JavaScript 1.5), whereas ActionScript 2.0 is based on the emerging ECMAScript 4 standard (as is the theoretical JavaScript 2.0). As we learned in the Preface, under "ActionScript 2.0 Versus ActionScript 1.0," this common heritage gives the two versions a strong family resemblance; they share the same syntax for most non-OOP features, such as loops, conditionals, and operators.
Although ActionScript 2.0 is now the preferred version of ActionScript, ActionScript 1.0 syntax continues to be fully supported by Flash Player 7 and is not deprecated. As we'll see shortly, you can author either ActionScript 1.0 or ActionScript 2.0 in Flash MX 2004 and Flash MX Professional 2004 (but you cannot author ActionScript 2.0 in Flash MX). With a few minor exceptions, noted throughout the text, ActionScript 2.0 code is also backward compatible with Flash Player 6. However, ActionScript 2.0 is not compatible with older versions such as Flash Player 5 or Flash Player 4.
If you're an ActionScript 1.0 programmer, you can think of ActionScript 2.0 as a syntactic façade over ActionScript 1.0. That is, both ActionScript 2.0 and ActionScript 1.0 compile to the same .swf bytecode (with a few minor additions for ActionScript 2.0). To the Flash Player, at runtime, there's effectively no difference between ActionScript 1.0 and ActionScript 2.0 (barring the aforementioned minor additions). For example, once an ActionScript 2.0 class, such as Rectangle , is compiled to a .swf file, it exists as a Function object at runtime, just as an older ActionScript 1.0 function declaration used as a class constructor would. Similarly, at runtime, an ActionScript 2.0 Rectangle instance (r) is given a _ _proto_ _ property that refers to Rectangle.prototype, again making it look to the Flash Player just like its ActionScript 1.0 counterpart.
But for the most part, you don't need to worry about these behind-the-scenes compiler and runtime issues. If you're moving to ActionScript 2.0 (and I think you should!), you can permanently forget ActionScript 1.0's prototype-based programming. In fact, most ActionScript 1.0 techniques for dynamically manipulating objects and classes at runtime are considered bad practice in ActionScript 2.0, and will actually lead to compiler errors when mixed with ActionScript 2.0 code. But never fear, this book highlights problematic ActionScript 1.0 practices and show you how to replace them with their modern ActionScript 2.0 counterparts.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Let's Go OOP
Now that we've had a taste of what ActionScript 2.0 has to offer, we can start our study of object-oriented programming with Flash in earnest. When you're ready to get your hands dirty, move on to Chapter 2!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Object-Oriented ActionScript
Ironically, Flash users who are new to object-oriented programming (OOP) are often familiar with many object-oriented concepts without knowing their formal names. This chapter demystifies some of the terminology and brings newer programmers up to speed on key OOP concepts. It also serves as a high-level overview of OOP in ActionScript for experienced programmers who are making their first foray into Flash development.
Traditional programming consists of various instructions grouped into procedures . Procedures perform a specific task without any knowledge of or concern for the larger program. For example, a procedure might perform a calculation and return the result. In a procedural-style Flash program, repeated tasks are stored in functions and data is stored in variables. The program runs by executing functions and changing variable values, typically for the purpose of handling input and generating output. Procedural programming is sensible for certain applications; however, as applications become larger or more complex and the interactions between procedures (and the programmers who use them) become more numerous, procedural programs can become unwieldy. They can be hard to maintain, hard to debug, and hard to upgrade.
Object-oriented programming (OOP) is a different approach to programming, intended to solve some of the development and maintenance problems commonly associated with large procedural programs. OOP is designed to make complex applications more manageable by breaking them down into self-contained, interacting modules. OOP lets us translate abstract concepts and tangible real-world things into corresponding parts of a program (the "objects" of OOP). It's also designed to let an application create and manage more than one of something, as is often required by user interfaces. For example, we might need 20 cars in a simulation, 2 players in a game, or 4 checkboxes in a fill-in form.
Properly applied, OOP adds a level of conceptual organization to a program. It groups related functions and variables together into separate
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Procedural Programming and Object-Oriented Programming
Traditional programming consists of various instructions grouped into procedures . Procedures perform a specific task without any knowledge of or concern for the larger program. For example, a procedure might perform a calculation and return the result. In a procedural-style Flash program, repeated tasks are stored in functions and data is stored in variables. The program runs by executing functions and changing variable values, typically for the purpose of handling input and generating output. Procedural programming is sensible for certain applications; however, as applications become larger or more complex and the interactions between procedures (and the programmers who use them) become more numerous, procedural programs can become unwieldy. They can be hard to maintain, hard to debug, and hard to upgrade.
Object-oriented programming (OOP) is a different approach to programming, intended to solve some of the development and maintenance problems commonly associated with large procedural programs. OOP is designed to make complex applications more manageable by breaking them down into self-contained, interacting modules. OOP lets us translate abstract concepts and tangible real-world things into corresponding parts of a program (the "objects" of OOP). It's also designed to let an application create and manage more than one of something, as is often required by user interfaces. For example, we might need 20 cars in a simulation, 2 players in a game, or 4 checkboxes in a fill-in form.
Properly applied, OOP adds a level of conceptual organization to a program. It groups related functions and variables together into separate classes , each of which is a self-contained part of the program with its own responsibilities. Classes are used to create individual objects that execute functions and set variables on one another, producing the program's behavior. Organizing the code into classes makes it easier to create a program that maps well to real-world problems with real-world components. Parts II and III of this book cover some of the common situations you'll encounter in ActionScript, and show how to apply OOP solutions to them. But before we explore applied situations, let's briefly consider the basic concepts of OOP.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Key Object-Oriented Programming Concepts
An object is a self-contained software module that contains related functions (called its methods ) and variables (called its properties). Individual objects are created from classes, which provide the blueprint for an object's methods and properties. That is, a class is the template from which an object is made. Classes can represent theoretical concepts, such as a timer, or physical entities in a program, such as a pull-down menu or a spaceship. A single class can be used to generate any number of objects, each with the same general structure, somewhat as a single recipe can be used to bake any number of muffins. For example, an OOP space fighting game might have 20 individual SpaceShip objects on screen at one time, all created from a single SpaceShip class. Similarly, the game might have one 2dVector class that represents a mathematical vector but thousands of 2dVector objects in the game.
The term instance is often used as a synonym for object. For example, the phrases "Make a new SpaceShip instance" and "Make a new SpaceShip object" mean the same thing. Creating a new object from a class is sometimes called instantiation .
To build an object-oriented program, we:
  1. Create one or more classes.
  2. Make (i.e., instantiate) objects from those classes.
  3. Tell the objects what to do.
What the objects do determines the behavior of the program.
In addition to using the classes we create, a program can use any of the classes built into the Flash Player. For example, a program can use the built-in Sound class to create Sound objects. An individual Sound object represents and controls a single sound or a group of sounds. Its setVolume( ) method can raise or lower the volume of a sound. Its
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
But How Do I Apply OOP?
Many people learn the basics of OOP only to say, "I understand the terminology and concepts, but I have no idea how or when to use them." If you have that feeling, don't worry, it's perfectly normal; in fact, it means you're ready to move on to the next phase of your learning—object-oriented design (OOD).
The core concepts of OOP (classes, objects, methods, properties, etc.) are only tools. The real challenge is designing what you want to build with those tools. Once you understand a hammer, nails, and wood, you still have to draw a blueprint before you can actually build a fence, a room, or a chair. Object-oriented design is the "draw a blueprint" phase of object-oriented programming, during which you organize your entire application as a series of classes. Breaking up a program into classes is a fundamental design problem that you'll face daily in your OOP work. We'll return to this important aspect of OOP regularly throughout this book.
But not all Flash applications need to be purely object-oriented. Flash supports both procedural and object-oriented programming and allows you to combine both approaches in a single Flash movie. In some cases, it's sensible to apply OOP only to a single part of your project. Perhaps you're building a web site with a section that displays photographs. You don't have to make the whole site object-oriented; you can just use OOP to create the photograph-display module. (In fact, we'll do just that in Chapter 5 and Chapter 7!)
So if Flash supports both procedural and object-oriented programming, how much of each is right for your project? To best answer that question, we first need to understand the basic structure of every Flash movie. The fundamental organizing structure of a Flash document (a .fla file) is the timeline , which contains one or more frames. Each frame defines the content that is displayed on the graphical canvas called the Stage . In the Flash Player, frames are displayed one at a time in a linear sequence, producing an animated effect—exactly like the frames in a filmstrip.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
On with the Show!
In this chapter, we summarized the core concepts of OOP in Flash. We're now ready to move on with the rest of Part I, where we'll study all of those concepts again in detail, applying them to practical situations along the way. If you're already quite comfortable with OOP and want to dive into some examples, see Chapter 5, Chapter 7, Chapter 11, and Chapter 12, and all of Part III, which contain in-depth studies of real-world object-oriented code.
Let's get started!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Datatypes and Type Checking
ActionScript 2.0 defines a wide variety of datatypes. Some datatypes are native to the language itself (e.g., String, Number, and Boolean). Others are included in the Flash Player and are available throughout all Flash movies (e.g., Color, Date, and TextField). Still other datatypes are defined by components that can be added individually to Flash movies (e.g., List, RadioButton, and ScrollPane).
For a primer on ActionScript's datatypes, see Chapter 3 of ActionScript for Flash MX: The Definitive Guide (O'Reilly), available online at http://moock.org/asdg/samples.
In addition to using ActionScript 2.0's datatypes, developers can add new datatypes to a program by creating classes (covered in Chapter 4) and interfaces (covered in Chapter 8). Every value in ActionScript 2.0 belongs to a datatype, whether built-in or programmer-defined. When we work with a value, we must use it only in ways supported by its datatype. For example, we can call getTime( ) on a Date object, but we must not call gotoAndPlay( ) on a Date object, because the Date class does not support the gotoAndPlay( ) method. On the other hand, we can call gotoAndPlay( ) on a movie clip because that method is defined by the MovieClip class.
In order for an object-oriented program to work properly, every operation performed on every object should succeed. That is, if a method is invoked on an object, the object's class must actually define that method. And if a property is accessed on an object, the object's class must define that property. If the object's class does not support the method or property, that aspect of the program will fail. Depending on how we write our code, either the failure will be silent (i.e., cause no error message), or it will cause an error message that appears in the Output panel. The error message helps us diagnose the problem.
We certainly strive to use objects appropriately. We don't intentionally call gotoAndPlay( ) on a Date object, because we know that the gotoAndPlay( ) method isn't supported by the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Static Typing?
There's plenty of debate about whether static typing (compile-time type checking) is better than dynamic typing (runtime type checking). But there's no question that a programmer benefits from being alerted to potential or actual type mismatch errors. Next to syntax errors (grammatical and typographical errors), datatype errors are the most common kind of error in an object-oriented program. If a syntax error occurs, a program won't compile. If a type mismatch error occurs, a program may be able to run, but it wouldn't likely be able to perform one or more requested operations. Such errors often lead to program failures. Some compilers merely warn of type mismatch errors but still allow compilation to continue. However, ActionScript 2.0's static typing facilities prevent the movie from compiling if type mismatch errors exist. Compared to ActionScript 1.0's complete lack of type checking, this is a great step forward for the language.
You must address all type mismatch errors to get your movie to compile. If type checking is new to you, you may feel that this requirement adds unnecessary work. You might be tempted to simply eliminate the datatype declarations that are causing the type mismatch errors in order to get your movie to compile. That's a little like going upstairs when your basement is flooded. Avoiding the problem doesn't solve anything in the long run. Here's a laundry list of reasons that explains why you should stay the course and learn to love type checking:
  • Type checking guarantees the validity of most operations at compile time, catching potential errors before they ever occur. Once a program type checks (i.e., compiles without producing type errors), most careless errors are eliminated, so you can focus on correcting any errors in logic.
  • Specifying type information throughout your code helps to ensure you follow your own OOP architectural plan. Similarly, it guarantees you'll use another developer's class as intended. If you misuse a class, you'll hear about it from the compiler.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Type Syntax
Now that we've had a general introduction to type checking in ActionScript 2.0, let's study the syntax more formally. ActionScript 2.0's compile-time type checking can be applied to:
  • A variable
  • A property
  • A function or method parameter
  • A function or method return value
To enable type checking for any of the preceding items, we declare the item's type using post-colon syntax, as discussed earlier and in the next section. Declaring an item's type tells the compiler what kind of data it should contain. Armed with that knowledge, the compiler can warn us of two possible error conditions:
  • If a value of an incompatible type is stored in a variable, passed as a function parameter, or returned by a function, the compiler generates a type mismatch error.
  • If a nonexistent property or method is accessed through a typed variable, function parameter, or function return value, the compiler generates an error explaining that the property or method cannot be found.
The compiler selectively type checks only items that have their types declared. Unfortunately, Flash MX 2004 does not provide a way to force the ActionScript compiler to report which items have no datatype declared. Hence, type errors can slip through if you're not vigilant about declaring datatypes. (For comparison, in Java, a program will not compile if any datatype declarations are missing.)
To declare the datatype of a variable or property, use the following syntax:
var variableOrPropertyName:datatype;
where variableOrPropertyName is the name of the variable or property, and
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compatible Types
The following discussion assumes an understanding of inheritance in OOP. If you're not familiar with that concept, you may want to skip this section for now and return to it once you've read Chapter 6.
Earlier we learned that a variable of one type can store only a value of a compatible type. Intuitively, we understand that the String type is incompatible with the Number type (that is, putting aside for a moment that it is possible to convert between strings and numbers, we know that a string is not a number). But the phrase "compatible type" has a very precise technical meaning. A type, X, is compatible with another type, Y, if X is of type Y, or if X is any subtype of Y.
For example, suppose we have a class, Ball, and a subclass, Basketball. A variable of type Ball can store a Basketball instance because the Basketball type is a subtype (i.e., subclass) of Ball:
var ball1:Ball = new Basketball( );  // Legal!
The preceding code works because the compiler knows that every Basketball instance has (through inheritance) all the properties and methods of the Ball class. The converse, however, is not true; every Ball instance does not necessarily have the properties and methods of the Basketball class. Therefore, the following code yields a compile-time type mismatch error:
var ball2:Basketball = new Ball( );  // Illegal!
On first glance, you might think that the preceding examples seem backward, but they are not. In the first example, we store a Basketball instance in the variable ball1, whose declared datatype is Ball. The compiler allows this even though the Basketball subclass might define methods and properties not supported by the Ball superclass. However, the compiler displays an error if we try to access a method or property on ball1 that isn't supported by the Ball class (i.e., the datatype of ball1) even if such method or property is defined for the Basketball class. For example, suppose that the Basketball subclass defines an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Built-in Dynamic Classes
We saw earlier that trying to dynamically add a property to the Date class generates a compile-time error in ActionScript 2.0. To allow new properties and methods to be added to a class's instances without generating a compile-time error, we can use a dynamic class. You can define your own dynamic classes, but some built-in classes are dynamic by default. Due partially to the architecture of the Flash Player and partially to the heritage of ActionScript 1.0, the following native ActionScript 2.0 classes are dynamic:
  • Array
  • ContextMenu
  • ContextMenuItem
  • Function
  • FunctionArguments (a.k.a. the Arguments object)
  • LoadVars
  • MovieClip
  • Object
  • TextField
When you attempt to access a nonexistent property or method on an object of one of the preceding dynamic classes, the ActionScript 2.0 compiler does not generate an error. For example, the following code yields no error:
var dataSender:LoadVars = new LoadVars( );
dataSender.firstName = "Rebecca";  // No error, even though 
                                   // the LoadVars class doesn't 
                                   // define the firstName property.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Circumventing Type Checking
We learned earlier that ActionScript 2.0's type checking is an "opt-in" system. That is, type checking occurs only when the programmer supplies type information (i.e., declares an item's datatype) in a program's source code. If you are sadistic and prefer to check your code manually for type errors, simply do not declare type information for variables, properties, parameters, and return values. When no type information is supplied for a data container, the compiler skips type checking for it. For example, the following code creates a variable, x, but does not declare x's datatype:
var x = 10;
Because the variable x is not typed, type checking is not (indeed cannot be) performed, and x's datatype can be changed without generating an error:
x = "hello";  // Change from Number to String.
Furthermore, accessing nonexistent properties and methods on x causes no error:
trace(x._width);   // No error. Returns undefined if _width doesn't exist.
x.flyToTheMoon( );  // No error.
                   // Fails silently if flyToTheMoon( ) doesn't exist.
Likewise, when a function or method parameter's type is not supplied, the parameter can accept values of any type without generating a compile-time error. And when a function's or method's return type is not supplied, the function or method can return values of any type without generating a compile-time error. The following code shows a method that declares no parameter types or return type. No matter what the types of the parameters, the method adds them together and returns the result. The result can legally belong to any datatype:
function combine (x, y) {
  return x + y;
}
// Pass values with different datatypes to x and y.
// No errors occur because the parameters x and y are not typed.
trace(combine(4,5));                   // Displays: 9
trace(combine("hello ", "world"));     // Displays: hello world
trace(combine(_root, "hello world"));  // Displays: _level0hello world
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Casting
In drama, when we say that an actor is "cast" in a role, we mean that the person will portray a particular character in a play or a movie. In programming, the term cast has very much the same meaning, but it applies to objects instead of people. When we cast an object in ActionScript 2.0, we make the object pretend to be an instance of another datatype. Casting is used to tell the compiler the type of an object when the compiler can't determine the object's type on its own.
To fully understand casting in ActionScript 2.0, you first need to understand inheritance, which we haven't covered yet. If you're new to the concept of inheritance, you may want to skip this section and return to it after reading Chapter 6.
The syntax of casting in ActionScript 2.0 is:
               Type(object);
where object is the object to cast and Type is the datatype to which the object will appear to belong.
Java and C++ developers accustomed to the cast syntax ( Type ) object should note that in ActionScript 2.0's cast syntax, the parentheses surround the object, not the type name. That is, ActionScript's type casting resembles the form of a function call.
Here's a very simple example of casting, in which we store a generic Object in the variable obj, then assign obj to the variable tf, whose type is TextField. Before assigning obj to tf, we cast obj to the TextField datatype:
var obj:Object   = new Object( );
var tf:TextField = TextField(obj);
For the sake of type checking, the expression TextField(obj) tricks the compiler into believing that obj is a TextField. Without the cast, the compiler would generate a type mismatch error. With the cast, the compiler generates no error because it considers the variable obj to be a TextField instance, which is compatible with the datatype of tf. Refer to the earlier discussion under "Compatible Types" for an explanation of why storing an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Datatype Information for Built-in Classes
When working with static typing and ActionScript 2.0's built-in classes, you must observe the declared datatypes for each class. For example, if you store a TextFormat object in a typed variable, you must use the correct datatypes when assigning values to its properties. The following code generates an error because the TextFormat.align property requires a String, but a Boolean is used:
var tf:TextFormat = new TextFormat( );
tf.align = true;  // Error! Boolean values not allowed.
Unfortunately, Macromedia's documentation does not provide type information for the methods and properties of the built-in classes nor for the Flash MX 2004 components. For your benefit, the type information is listed in Appendix A.
Type information can also be retrieved from the source code of the classes in the installation folder for Flash MX 2004, as follows:
/Macromedia/Flash MX 2004/en/First Run/Classes
Component class definitions are found in the /mx/ directory, one directory below the /Classes/ directory listed previously.
Note that although source code for components is included in full, the built-in class definitions are intrinsic, meaning that they do not include method bodies or other implementation information. They do, however, contain datatype information as specified in Appendix A. For more details on intrinsic definitions, see Chapter 6.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ActionScript 2.0 Type Checking Gotchas
ActionScript 2.0's type checking system has its quirks and limitations. The remainder of this chapter covers some anomalies to keep in mind when working with ActionScript 2.0.
To create a global variable in ActionScript, we add a property to the _global object, as follows:
_global.varname = value;
The preceding property-definition syntax is a carryover from ActionScript 1.0 and does not support datatype declarations. It is, therefore, impossible to use type checking with a global variable. For example, this causes a compile-time syntax error:
_global.author:String = "moock";  // Output panel displays: Syntax error.
As an alternative, you should consider using a class property in lieu of globals, as discussed under "Property Attributes" in Chapter 4.
When code is placed on a frame in a timeline, the properties and methods of movie clips are not type checked. For example, the following attempt to assign a String value to the numeric property _y does not generate a compile-time type mismatch error when the code is placed on a frame in a timeline:
_root._y = "test";  // No error. (Should be a type mismatch error.)
Similarly, the following attempt to store a number returned by getBytesLoaded( ) in a String variable does not generate an error when the code is placed on a frame:
// No error. (Should be a type mismatch error.)
var msg:String = _root.getBytesLoaded( );
Furthermore, assigning the current MovieClip instance (this) to a non-MovieClip variable or passing the current MovieClip instance (this) to a non-MovieClip function parameter causes no error. For example, when placed on a frame in a timeline, the following examples yield no error:
var x:String = this;  // No error. (Should be a type mismatch error.)

function square(x:Number):Number {
  return x * x;
}
square(this);  // No error. (Should be a type mismatch error.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Up Next: Creating Classes—Your Own Datatypes!
As we've seen in this chapter, datatypes and type checking are an essential part of programming in ActionScript 2.0. Now that you're familiar with how datatypes work and how they help you write better code, it's time to move on. In Chapter 4 you'll learn how to define your own datatypes by creating classes. Learning to create a class is the first hands-on step down the path of the object-oriented programmer.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Classes
This chapter covers the syntax and theory behind classes in ActionScript 2.0 and assumes a prior basic understanding of the concepts discussed in Chapter 2. Classes are the foundational structure of all object-oriented programs, making them arguably the most important aspect of OOP. As such, classes are predictably intricate. This chapter is correspondingly lengthy and detailed but, even so, newer programmers can use it to learn the basics of creating and using classes.
If this is your first real exposure to programming with classes, you may want to concentrate on the first few pages of each of the following sections:
  • "Defining Classes"
  • "Constructor Functions (Take 1)"
  • "Properties"
  • "Methods"
  • "Completing the Box Class"
Then you can dive right into Chapter 5, which shows, step-by-step, how to create a real-world class in the Flash authoring environment. We'll address the big-picture questions in Chapter 5. (I decided to cover the syntax and mechanics first so you'd have a strong foundation moving forward.)
Just remember to return to the present chapter whenever you need detailed reference material on implementing and using classes in ActionScript 2.0.
A class is a template for the creation of objects (or, synonymously, instances). Classes are the building blocks of an object-oriented program. Every object-oriented application includes at least one class, and typical applications include several or dozens of classes. From classes, a program generates the objects that determine the things the program can do.
We saw earlier that classes are used to group properties and methods into a coherent bundle. A typical class might define a spaceship or a scrollbar in terms of how it looks, what it does when the user clicks on it, or how it interacts with other objects.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining Classes
A class is a template for the creation of objects (or, synonymously, instances). Classes are the building blocks of an object-oriented program. Every object-oriented application includes at least one class, and typical applications include several or dozens of classes. From classes, a program generates the objects that determine the things the program can do.
We saw earlier that classes are used to group properties and methods into a coherent bundle. A typical class might define a spaceship or a scrollbar in terms of how it looks, what it does when the user clicks on it, or how it interacts with other objects.
To create, or define, an ActionScript 2.0 class, we use a class declaration, which starts with the class keyword, as follows:
class ClassIdentifier {
}
where ClassIdentifier is the name of the class (which, by convention, should start with a capital letter). For example, the following code defines a class named Box, albeit one that doesn't do anything interesting yet:
class Box {
}
We'll use the Box class as an example throughout this chapter. Eventually, our Box will represent and control an on-screen rectangular shape. You might use a similar class in a drawing-tool application. The Box class is intentionally generic, allowing you to map its concepts onto your own classes. In subsequent chapters, we'll explore more applied scenarios.
A class definition must reside in an external plain text file that has the extension .as. Use of the class keyword anywhere else—such as on a keyframe or a button—generates a compile-time error. Furthermore, each .as file can contain only one class definition and must have a filename exactly matching the name of the class it contains (case sensitivity matters!).
For example, the Box class must be stored in a file named Box.as. If Box.as erroneously contains a class named, say,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constructor Functions (Take 1)
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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Properties
As we learned in Chapter 2, classes use properties to store information. But some information relates to a class as a whole (e.g., the default size for all SpaceShip objects) and some information relates to individual objects (e.g., the current speed or position of each SpaceShip instance). Consequently, properties come in different varieties:
Class properties
Named data containers associated with a class
Instance properties
Named data containers associated with objects (i.e., instances of the class)
Together, class properties and instance properties are sometimes referred to as fixed properties , in opposition to the dynamic properties discussed earlier. Again, dynamic properties are generally considered bad OOP form and should be avoided, although they are necessary for things like named array elements.
In our coverage of properties, we'll concentrate first on instance properties because they are by far the most common type of property. We'll also largely ignore dynamic properties because they are considered bad form in ActionScript 2.0 despite being somewhat common in ActionScript 1.0.
In ActionScript and ECMAScript 4, instance properties are sometimes called instance variables, and class properties are sometimes called class variables (following Java's terminology). Instance variables and class variables should not be confused with the normal ActionScript variables that can be created without reference to an object or a class. To keep things clear, we'll avoid the terms instance variable and class variable, but you should expect to see them in other technical documentation and even in ActionScript compiler error messages. Furthermore, to avoid awkward wordiness, we'll often use the shorter term,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Methods
Methods are functions that determine the behavior of a class. They implement the tasks that instances of the class or the class itself can perform. For example, ActionScript's built-in Sound class has a method named loadSound( ) that can retrieve an external MP3 file for playback in the Flash Player.
To define methods for our own classes, we use the