Preface

ActionScript is the official programming language of Adobe’s Flash platform. While originally conceived as a simple tool for controlling animation, ActionScript has since evolved into a sophisticated programming language for creating content and applications for the Web, mobile devices, and desktop computers. True to its roots, ActionScript can be used in many different ways by many different kinds of programmers and content producers. For example, an animator might use just a few lines of ActionScript to pause the playback of a web animation. Or, an interface designer might use a few hundred lines of ActionScript to add interactivity to a mobile phone interface. Or, an application developer might use thousands of lines of ActionScript to create an entire email-reading application for web browser and desktop deployment.

This book covers ActionScript programming fundamentals in truly exhaustive detail, with extreme clarity and precision. Its unparalleled accuracy and depth is the result of an entire decade of daily ActionScript research, real-world programming experience, and unmitigated insider-access to Adobe’s engineers. Every word of this book has been carefully reviewed—in many cases several times over—by key members of Adobe’s engineering staff, including those on the Flash Player, Flex Builder, and Flash authoring teams. (See the "Acknowledgments" section at the end of this preface.)

Beginners Welcome

This book explores ActionScript from a programmer’s perspective but assumes no prior programming knowledge. If you have never programmed before, start with Chapter 1. It will guide you through the very basics of ActionScript, demystifying terms like variable, method, class, and object. Then continue through the book sequentially. Each chapter builds on the previous chapter’s concepts, introducing new topics in a single, prolonged narrative that will guide you on your journey to ActionScript proficiency.

Note, however, that if you are a designer who simply wants to learn how to control animations in the Flash authoring tool, you probably don’t need this book. Adobe’s documentation will tell what you need to know. Come back to this book when you want to learn how to add logic and programmatic behavior to your content.

Expert Guidance

If you already have existing ActionScript experience, this book will help you fill in gaps in your knowledge, rethink important concepts in formal terms, and understand difficult subjects through plain, careful language. Consider this book an ActionScript expert that sits with you at your desk. You might ask it to explain the subtleties of ActionScript’s event architecture, or unravel the intricacies of Flash Player’s security system, or demonstrate the power of ActionScript’s native XML support (E4X). Or you might turn to this book for information on under-documented topics, such as namespaces, embedded fonts, loaded-content access, class-library distribution, garbage collection, and screen updates.

This book is a true developer’s handbook, packed with practical explanations, insightful warnings, and useful example code that demonstrates how to get the job done right.

What’s In This Book

This book is divided into three parts.

Part I, provides exhaustive coverage of the core ActionScript language, covering object-oriented programming, classes, objects, variables, methods, functions, inheritance, datatypes, arrays, events, exceptions, scope, namespaces, XML. Part I closes with a look at Flash Player’s security architecture.

Part II, explores techniques for displaying content on screen and responding to input events. Topics covered include the Flash runtime display API, hierarchical event handling, mouse and keyboard interactivity, animation, vector graphics, bitmap graphics, text, and content loading operations.

Part III, focuses on ActionScript code-production issues. Topics covered include combining ActionScript with assets created manually in the Flash authoring tool, using the Flex framework in Flex Builder 2, and creating a custom code library.

This book closes with a walkthrough of a fully functional example program—a virtual zoo.

What’s Not In This Book

The ActionScript ecosystem is vast. No single book can cover it all. Noteworthy topics that are not covered extensively in this book include:

  • MXML

  • The Flex framework

  • Flex Data Services

  • The Flash authoring tool’s built-in components

  • Flash Media Server

  • Flash Remoting

  • ActionScript’s regular expression support

For information on these topics, see Adobe’s documentation and O’Reilly’s Adobe Developer Library, at http://www.oreilly.com/store/series/adl.csp.

Authoring Tool Agnosticism

This book teaches core ActionScript concepts that apply to any ActionScript 3.0 authoring environment and any runtime that supports ActionScript 3.0. As much as possible, this book avoids tool-specific development topics and focuses on programming concepts rather than tool usage. That said, Chapter 29 covers ActionScript’s use in the Flash authoring tool, and Chapter 30 covers the very basics of using the Flex framework in Flex Builder 2. Likewise, Chapter 7 describes how to compile a program using various authoring tools (Flash, Flex Builder 2, and mxmlc).

Now let’s turn our attention to the ActionScript language itself. The following sections provide a technical introduction to ActionScript 3.0 for experienced programmers. If you are completely new to programming, you should skip down to “Typographical Conventions” and then proceed to Chapter 1.

ActionScript Overview

ActionScript 3.0 is an object-oriented language for creating applications and scripted multimedia content for playback in Flash client runtimes (such as Flash Player and Adobe AIR). With a syntax reminiscent of Java and C#, ActionScript’s core language should be familiar to experienced programmers. For example, the following code creates a variable named width, of type int (meaning integer), and assigns it the value 25:

var width:int = 25;

The following code creates a for loop that counts up to 10:

for (var i:int = 1; i <= 10; i++) {
  // Code here runs 10 times
}

And the following code creates a class named Product:

// The class definition
public class Product {
  // An instance variable of type Number
  var price:Number;

  // The Product class constructor method
  public function Product () {
    // Code here initializes Product instances
  }

  // An instance method
  public function doSomething ():void {
    // Code here executes when doSomething() is invoked
  }
}

The Core Language

ActionScript 3.0’s core language is based on the ECMAScript 4th edition language specification, which is still under development as of May 2007.

Tip

The ECMAScript 4 specification can be viewed at http://developer.mozilla.org/es4/spec/spec.html. The ActionScript 3.0 specification can be viewed at http://livedocs.macromedia.com/specs/actionscript/3.

In the future, ActionScript is expected to be a fully conforming implementation of ECMAScript 4. Like ActionScript, the popular web browser language JavaScript is also based on ECMAScript. The future Firefox 3.0 web browser is expected to implement JavaScript 2.0 using the same code base as ActionScript, which was contributed to the Mozilla Foundation by Adobe in November 2006 (for information, see http://www.mozilla.org/projects/tamarin).

ECMAScript 4 dictates ActionScript’s basic syntax and grammar—the code used to create things such as expressions, statements, variables, functions, classes, and objects. ECMAScript 4 also defines a small set of built-in datatypes for working with common values (such as String, Number, and Boolean).

Some of ActionScript 3.0’s key core-language features include:

  • First-class support for common object-oriented constructs, such as classes, objects, and interfaces

  • Single-threaded execution model

  • Runtime type-checking

  • Optional compile-time type-checking

  • Dynamic features such as runtime creation of new constructor functions and variables

  • Runtime exceptions

  • Direct support for XML as a built-in datatype

  • Packages for organizing code libraries

  • Namespaces for qualifying identifiers

  • Regular expressions

All Flash client runtimes that support ActionScript 3.0 share the features of the core language in common. This book covers the core language in its entirety, save for regular expressions.

Flash Runtime Clients

ActionScript programs can be executed in three different client runtime environments: Adobe AIR, Flash Player, and Flash Lite.

Adobe AIR

Adobe AIR runs Flash-platform applications intended for desktop deployment. Adobe AIR supports SWF-format content, as well as content produced with HTML and JavaScript. Adobe AIR must be installed directly on the end user’s computer at the operating-system level.

For more information, see http://www.adobe.com/go/air.

Flash Player

Flash Player runs Flash-platform content and applications intended for web deployment. Flash Player is the runtime of choice for embedding SWF-format content on a web page. Flash Player is typically installed as a web browser add-on but can also run in standalone mode.

Flash Lite

Flash Lite runs Flash-platform content and applications intended for mobile-device deployment. Due to the performance limitations of mobile devices, Flash Lite typically lags behind Flash Player and Adobe AIR in both speed and feature set. As of June 2007, Flash Lite does not yet support ActionScript 3.0.

The preceding Flash client runtimes offer a common core set of functionality, plus a custom set of features that cater to the capabilities and security requirements of the runtime environment. For example, Adobe AIR, Flash Player, and Flash Lite all use the same syntax for creating a variable, but Adobe AIR includes window-management and filesystem APIs, Flash Lite can make a phone vibrate, and Flash Player imposes special web-centric security restrictions to protect the end user’s privacy.

Runtime APIs

Each Flash client runtime offers its own built-in set of functions, variables, classes, and objects—known as its runtime API. Each Flash client runtime’s API has its own name. For example, the Flash client runtime API defined by Flash Player is known as the Flash Player API.

All Flash client runtime APIs share a core set of functionality in common. For example, every Flash client runtime uses the same basic set of classes for displaying content on screen and for dispatching events.

Key features shared by all Flash client runtime APIs include:

  • Graphics and video display

  • A hierarchical event architecture

  • Text display and input

  • Mouse and keyboard control

  • Network operations for loading external data and communicating with server-side applications

  • Audio playback

  • Printing

  • Communicating with external local applications

  • Programming utilities

This book covers the first five of the preceding items. For information on other specific Flash client runtime APIs, consult the appropriate product documentation.

Components

In addition to the Flash client runtime APIs, Adobe also offers two different sets of components for accomplishing common programming tasks and building user interfaces. Flex Builder 2 and the free Flex 2 SDK include the Flex framework, which defines a complete set of user interface controls, such as RadioButton, CheckBox, and List. The Flash authoring tool provides a similar set of user interface components. The Flash authoring tool’s components combine code with manually created graphical assets that can be customized by Flash developers and designers.

Both the Flex framework and the Flash authoring tool’s component set are written entirely in ActionScript 3.0. The user interface components in the Flex framework generally have more features than those in the Flash authoring tool’s component set and, therefore, also have a larger file size.

Warning

User interface components from the Flex framework cannot be used in the Flash authoring tool, but user interface components from the Flash authoring tool can be used (both legally and technically) with Flex Builder 2 and mxmlc.

This book does not cover component use or creation in ActionScript. For information on components, see the appropriate product documentation.

The Flash File Format (SWF)

ActionScript code must be compiled into a .swf file for playback in one of Adobe’s Flash client runtimes. A .swf file can include both ActionScript bytecode and embedded assets (graphics, sound, video, and fonts). Some .swf files contain assets only and no code, while others contain code only and no assets. A single ActionScript program might reside entirely within a single .swf file, or it might be broken into multiple .swf files. When a program is broken into multiple .swf files, one specific .swf file provides the program point of entry, and loads the other .swf files as required. Breaking a complex program into multiple .swf files makes it easier to maintain and, for Internet-delivered applications, can give the user faster access to different sections of the program.

ActionScript Development Tools

Adobe offers the following tools for creating ActionScript code:

Adobe Flash

http://www.adobe.com/go/flash/

A visual design and programming tool for creating multimedia content that integrates graphics, video, audio, animation, and interactivity. In Adobe Flash, developers create interactive content by combining ActionScript code with animation, manually created content, and embedded assets. Adobe Flash is also known as the Flash authoring tool. As of June 2007, the latest version of the Flash authoring tool is Flash CS3 (Version 9 of the software).

Adobe Flex Builder

http://www.adobe.com/products/flex/productinfo/overview/

A development tool for producing content using either pure ActionScript or MXML, an XML-based language for describing user interfaces. Flex Builder includes a development framework known as the Flex framework, which provides an extensive set of programming utilities and a library of skinnable, styleable user-interface controls. Based on Eclipse, the popular open source programming tool, Flex Builder 2 can be used in either hand-coding mode or in a visual-development mode similar to Microsoft’s Visual Basic.

Adobe Flex 2 SDK

http://www.adobe.com/go/flex2_sdk

A free command-line toolkit for creating content using either pure ActionScript 3.0 or MXML. The Flex 2 SDK includes the Flex framework and a command-line compiler, mxmlc (both of which are also included with Adobe Flex Builder 2). Using the Flex 2 SDK, developers can create content for free in the programming editor of their choice. (For a wide variety of open source tools and utilities for ActionScript development, see http://osflash.org.)

This Book’s Example Files

The official companion web site for this book is:

http://moock.org/eas3

You can download the example files for this book at:

http://moock.org/eas3/examples

Note that most of the examples in this book are presented in the context of an enclosing main class, which is intended to be compiled as a .fla file’s document class (Flash authoring tool) or a project’s default application class (Flex Builder).

Using Code Examples

This book is here to help you get your job done. In general, you can use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: "Essential ActionScript 3.0 by Colin Moock. Copyright 2007 O’Reilly Media, Inc., 0-596-52694-6”.

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Typographical Conventions

In order to indicate the various syntactic components of ActionScript, this book uses the following conventions:

Menu options

Menu options are shown using the → character, such as File → Open.

Constant width

Indicates code examples, code snippets, variable names, and parameter names.

Italic

Indicates function names, method names, class names, package names, URLs, filenames, datatypes, keywords, objects, and file suffixes such as .swf. In addition to being italicized in the body text, method and function names are also followed by parentheses, such as duplicateMovieClip( ).

Constant width bold

Indicates text that you must enter verbatim when following a step-by-step procedure. Constant width bold is also sometimes used within code examples for emphasis, such as to highlight an important line of code in a larger example.

Constant width italic

Indicates code that you must replace with an appropriate value (e.g., yournamehere).

Tip

This is a tip. It contains useful information about the topic at hand, often highlighting important concepts or best practices.

Warning

This is a warning. It helps you solve and avoid annoying problems. Ignore at your own peril.

Note

This is a note about ActionScript 2.0. It compares and contrasts ActionScript 2.0 with ActionScript 3.0, helping you to migrate to ActionScript 3.0 and to understand important differences between the two versions of the language.

Coding and vocabulary conventions used in this book include:

  • The keyword this is written in constant-width font because it is an implicit parameter passed to methods and functions.

  • In general, the keyword this is not included when making reference to identifiers from within instance methods. However, this is used to disambiguate instance variables and instance methods from parameters and local variables.

  • When discussing accessor methods and mutator methods, this book avoids the traditional terms accessor, mutator, getter, and setter. Instead, this book uses the unofficial terms retriever method and modifier method. See Chapter 3.

  • In a class definition that contains static variables, static methods, instance variables, instance methods, and a constructor method, this book lists the static variables first, followed by the static methods, the instance variables, the class constructor method, and finally, the instance methods.

  • This book uses ALL CAPITAL LETTERS for constant names.

  • When referring to static variables and static methods, this book always includes the name of the class that defines the variable or method.

  • Unless otherwise stated, function closures are referred to by the shorter term function. See Chapter 5 for a description of the difference between the two terms.

  • This book assumes that all code is compiled in strict mode. Furthermore, after Chapter 7, this book supplies type annotations for all variables, parameters, and return values.

  • Event listeners in this book are named using the format eventNameListener, where eventName is the string name of the event.

How to Contact Us

We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made mistakes!). Please let us know about any errors you find, as well as your suggestions for future editions, by writing to:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)

We have a web page for the book, where we list errata, examples, or any additional information. You can access this page at:

http://www.oreilly.com/catalog/9780596526948

To comment or ask technical questions about this book, send email to:

For more information about our books, conferences, software, Resource Centers, and the O’Reilly Network, see our web site at:

http://www.oreilly.com

Acknowledgments

This book could not have been written without the abundant trust and very active support of both Adobe and O’Reilly. In the summer of 2005, in a meeting with Steve Weiss, Lisa Friendly, and Mike Chambers, I agreed to write a new book called Essential ActionScript 3.0. The book was originally billed as “a short update to Essential ActionScript 2.0.” But as the ActionScript 3.0 language evolved, Essential ActionScript 3.0 become a full work of its own. Patiently and faithfully, Adobe and O’Reilly watched the book increase vastly in scope, and agreed to let the publication deadline creep from nine months to two years. Throughout the entire process, I truly believed we were making the right choice, and I’m honored that Adobe and O’Reilly agreed.

Throughout this book’s writing, Adobe graciously furnished me with full access to internal resources and official engineering time for technical reviews. I owe great thanks to JuLee Burdekin and Francis Cheng from Adobe’s documentation team. JuLee and Francis coordinated my efforts internally at Adobe and answered a seemingly endless stream of questions.

Dozens of Adobe employees provided me with information and instruction during this book’s research. I am deeply grateful to all of them, and would especially like to thank the following:

  • Francis Cheng was a constant source of information on the core language and provided invaluable feedback on Essential ActionScript 3.0’s manuscript. Francis sits on the ECMAScript 4 committee and is one of the authors of the ActionScript 3.0 specification.

  • Jeff Dyer consistently took time out of his schedule to help clarify core-language concepts and investigate bugs. Jeff is one of the principal developers of the ActionScript 3.0 compiler, the principal author of the ActionScript 3.0 specification, and a key member of the ECMAScript 4 committee.

  • Deneb Meketa patiently endured my misunderstanding of Flash Player’s security system. Through phone calls and emails that spanned more than a month of intensive research, Deneb managed to bring clarity to Chapter 19. Deneb is the engineer responsible for implementing security in Flash Player.

  • Jeff Mott, Flash Player engineer, consistently offered extensive, near instant responses to my questions about ActionScript’s event system.

  • Jim Corbett, Flash Player engineer, helped me understand many display list and event-loading subtleties.

  • Rebecca Sun, Flash authoring engineer, answered many questions about the links between the ActionScript 3.0 compiler and Flash CS3. She also listened openly to suggestions, and endured my frequent spontaneous requests for information over instant messenger.

  • Lee Thomason, Flash Player Architect, gave me a personal education in Flash Player’s text rendering engine.

  • Roger Gonzalez, Flex Compiler Architect, regularly fielded my questions on class loading and the Flex compiler.

  • Werner Sharp, Flash Player engineer, explained many subtle nuances of bitmap programming in ActionScript.

  • Paul Betlem, Senior Director of Flash Player Engineering, helped facilitate the technical review process and reviewed several chapters himself.

  • Mike Chambers, Senior Product Manager of Developer Relations for Adobe AIR, provided regular technical information, and helped nurture the Essential ActionScript 3.0 project from its earliest stages.

  • Gary Grossman, the original creator of ActionScript, taught me much of what I know about programming for the Flash platform. In August 2006, Gary teamed up with the inventors of Flash (Jon Gay and Robert Tatsumi) to co-found a new company, Software as Art. See http://www.softwareasart.com.

Other Adobe staff, past and present, that I’m honored to know and work with include Mike Downey, Kevin Lynch, Paul Betlem, Edwin Smith, Christine Yarrow, Jeff Kamerer, Nigel Pegg, Matt Wobensmith, Thomas Reilly, Jethro Villegas, Rob Dixon, Jeff Swartz, Waleed Anbar, Chris Thilgen, Gilles Drieu, Nivesh Rajbhandari, Tei Ota, Akio Tanaka, Sumi Lim, Troy Evans, John Dowdell, Bentley Wolfe, Tinic Uro, Michael Williams, Sharon Seldon, Jonathan Gay, Robert Tatsumi, Pete Santangeli, Mark Anders, John Nack, Matt Chotin, Alex Harui, Gordon Smith, Sho Kuwamoto, Craig Goodman, Stefan Gruenwedel, Deepa Subramaniam, Ethan Malasky, Sean Kranzberg, Michael Morris, Eric Wittman, Jeremy Clark, and Janice Pearce.

Table 1 gives a statistical view of the depth of gratitude I owe this book’s official technical reviewers.

Table 1. Adobe reviewers

Reviewer

Title

Chapters reviewed

Number of emails fielded

Deneb Meketa

Computer Scientist, Flash Platform

17

75

Erica Norton

Senior Quality Engineer, Flash Player

14, 19, 21, 22

3

Francis Cheng

Senior Technical Writer

1–11, 13, 15, 16, 18

334

Jeff Dyer

Compiler Architect, ActionScript Language Group

17

106

Jeff Mott

Computer Scientist, Flash Player Engineering

12, 20–25

85

Jim Corbett

Senior Computer Scientist, Flash Player Engineering

20, 23, 24, 28

52

Lee Thomason

Architect, Flash Player

25, 27

33

Mike Chambers

Senior Product Manager, Developer Relations,

Adobe AIR

1

89

Mike Richards

Computer Scientist, Mobile and Devices

22–26

9

Paul Robertson

ActionScript Developer/Writer

1, 2, 24, 27–31

14

Paul Betlem

Senior Director, Flash Player Engineering

20, 27, 26

19

Rebecca Sun

Computer Scientist, Flash Authoring

7, 29, 31

60

Robert Penner

Senior Engineer, Flash Authoring

18, 23–25

16

Roger Gonzalez

Flex Compiler Architect

25, 30, 31

64

Werner Sharp

Senior Computer Scientist, Flash Player Engineering

18, 22

35

Thanks to Robyn Thomas, this book’s editor, who reviewed and polished the manuscript with great speed and precision. Thanks also to all of the members of O’Reilly’s management, editorial, production, interior design, art, marketing, and sales teams including Tim O’Reilly, Steve Weiss, and Karen Montgomery. And thanks to the copy editor, Philip Dangler, for helping to ensure the text’s consistency, readability, and accuracy.

In addition to being technically reviewed by Adobe staff, this book was also inspected for accuracy and quality by a keen group of beta readers, including Brett Walker, Chafic Kazoun, Derek McKenna, Edwin van Rijkom, Greg Burch, Jim Armstrong, Jon Williams, Mark Jonkman, Matthew Keefe, Mauro Di Blasi, Ralf Bokelberg, Ric Ewing, Robin Debreuil, and Victor Allen. The beta readers were indispensable, catching a great number of inconsistencies and subtle code errors. Mark Jonkman bears special mention for his extremely meticulous examination of the manuscript and its code examples.

Two mentors who helped shape me as a programmer and a writer are Bruce Epstein and Derek Clayton. Bruce was the editor for all of my previous books, and his rich lessons still inform every word I write. Derek is the creator of moock.org’s Unity multiuser server (http://www.moock.org/unity), and a regular source of programming inspiration and friendship.

Of course, no book on any ECMAScript-based language is complete without acknowledging Brendan Eich’s pioneering of JavaScript and ongoing development of ECMAScript. Thanks Brendan!

Finally, love and peace to the following for their love and friendship: James Porter, Graham Barton, Joe Duong, Tommy Jacobs, Wendy Schaffer, Andrew Harris, Dave Luxton, Dave Komlos, Marco Crawley, Eric Liphardt, Ken Reddick, Mike Linkovich, Matt Wearn, Mike Dobell, Mike “Nice,” Hoss Gifford, Erik Natzke, Jared Tarbell, Marcos Weskamp, Dan Albritton, Francis Bourre, Thijs Triemstra, Veronique Brossier, Saima Khokhar, Amit Pitaru, James Patterson, Joshua Davis, Branden Hall, Robert Hodgin, Shin Matsumura, Yugo Nakamura, Claus Whalers, Darron Schall, Mario Klingeman, Fumio Nonaka, Robert Reinhardt, Grant Skinner, and the Moocks.

—Colin Moock

March 2007

Toronto, Canada

Get Essential ActionScript 3.0 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.