If this guide is distributed with software that includes an end-user agreement, this guide, as well as the software described in it, is
furnished under license and may be used or copied only in accordance with the terms of such license. Except as permitted by any
such license, no part of this guide may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means,
electronic, mechanical, recording, or otherwise, without the prior written permission of Adobe Systems Incorporated. Please note
that the content in this guide is protected under copyright law even if it is not distributed with software that includes an end-user
license agreement.
The content of this guide is furnished for informational use only, is subject to change without notice, and should not be
construed as a commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability
for any errors or inaccuracies that may appear in the informational content contained in this guide.
Please remember that existing artwork or images that you may want to include in your project may be protected under copyright
law. The unauthorized incorporation of such material into your new work could be a violation of the rights of the copyright
owner. Please be sure to obtain any permission required from the copyright owner.
Any references to company names in sample templates are for demonstration purposes only and are not intended to refer to any
actual organization.
Adobe, the Adobe logo, Flex, Flex Builder and Flash Player are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries. ActiveX and Windows are either registered trademarks or trademarks of
Microsoft Corporation in the United States and other countries. Macintosh is a trademark of Apple Computer, Inc., registered in
the United States and other countries. All other trademarks are the property of their respective owners.
Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com).
Sorenson™ Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA
Notice to U.S. government end users. The software and documentation are “Commercial Items,” as that term is defined at 48
C.F.R. §2.101, consisting of “Commercial Computer Software” and “Commercial Computer Software Documentation,” as such
terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R.
§§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software
Documentation are being licensed to U.S. Government end users (a) only as Commercial items and (b) with only those rights as
are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright
laws of the United States. Adobe Systems Incorporated, 345 Park Avenue, San Jose, CA 95110-2704, USA. For U.S.
Government End Users, Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the
provisions of Executive Order 11246, as amended, Section 402 of the Vietnam Era Veterans Readjustment Assistance Act of
1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the regulations at 41 CFR Parts 60-1
through 60-60, 60-250 ,and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be
incorporated by reference.
This manual provides a foundation for developing applications in ActionScript 3.0. To best
understand the ideas and techniques described, you should already be familiar with general
programming concepts such as data types, variables, loops, and functions. You should also
understand basic object-oriented programming concepts like classes and inheritance. Prior
knowledge of ActionScript 1.0 or ActionScript 2.0 is helpful but not necessary.
Part 2, “Core ActionScript 3.0 Data Types
and Classes”
Part 3, “Flash Player APIs”Describes important features that are
The manual contains numerous sample files for important or commonly used classes to
demonstrate application programming concepts for those APIs. Sample files are packaged in
ways to make them easier to load and use with Adobe® Flex™ Builder 2 and may include
wrapper files. However, the core sample code is pure ActionScript 3.0 that you can use in
whichever development environment you prefer.
ActionScript 3.0 can be written and compiled a number of ways, including:
■ Using the Adobe Flex Builder 2 development environment
■ Using any text editor and a command-line compiler, such as the one provided with Flex
Builder 2
■ Using the Adobe® Flash® CS3 authoring tool from Adobe
For more information about ActionScript development environments, see Chapter 1,
“Introduction to ActionScript 3.0.”
Discusses core ActionScript 3.0 concepts,
including language syntax, statements and
operators, the ECMAScript edition 4 draft
language specification, object-oriented
ActionScript programming, and the new
approach to managing display objects on the
Adobe
® Flash® Player 9 display list.
Describes top-level data types in ActionScript
3.0 that are also part of the ECMAScript draft
specification.
implemented in packages and classes specific to
Adobe Flash Player 9, including event handling,
networking and communications, file input and
output, the external interface, the application
security model, and more.
12About This Manual
Page 13
To understand the code samples in this manual, you don’t need to have prior experience using
integrated development environments for ActionScript, such as Flex Builder or the Flash
authoring tool. You will, however, want to refer to the documentation for those tools to learn
how to use them to write and compile ActionScript 3.0 code. For more information, see
“Accessing ActionScript documentation” on page 13.
Accessing ActionScript documentation
Because this manual focuses on describing ActionScript 3.0, which is a rich and powerful
object-oriented programming language, it does not extensively cover the application
development process or workflow within a particular tool or server architecture. So in
addition to Programming ActionScript 3.0, you’ll want to consult other sources of
documentation as you design, develop, test, and deploy ActionScript 3.0 applications.
ActionScript 3.0 documentation
This manual familiarizes you with the concepts behind the ActionScript 3.0 programming
language and gives you implementation details and samples illustrating important language
features. However, this manual is not a complete language reference. For that, see the
ActionScript 3.0 Language Reference, which describes every class, method, property, and event
in the language. The ActionScript 3.0 Language Reference provides detailed reference
information about the core language, Flex MXML classes and components (in the mx
packages), and Flash Player APIs (in the flash packages).
Accessing ActionScript documentation13
Page 14
Flex documentation
If you use the Flex development environment, you may want to consult these manuals:
BookDescription
Flex 2 Developer’s GuideDescribes how to develop your dynamic web
applications.
Getting Started with Flex 2Contains an overview of Flex features and
application development procedures.
Building and Deploying Flex 2 ApplicationsDescribes how to build and deploy Flex
applications.
Creating and Extending Flex 2 Components Describes how to create and extend Flex
components.
Migrating Applications to Flex 2Provides an overview of the migration process,
as well as detailed descriptions of changes in
Flex and ActionScript.
Using Flex Builder 2Contains comprehensive information about all
Flex Builder features, for every level of Flex
Builder users.
ActionScript 3.0 Language ReferenceProvides descriptions, syntax, usage, and code
examples for the Flex API.
Developer Center
The Adobe Developer Center is a your resource for up-to-the-minute information on
ActionScript, articles about real-world application development, and information about
important emerging issues. View the Developer Center at www.adobe.com/devnet/.
14About This Manual
Page 15
CHAPTER 1
Introduction to
ActionScript 3.0
This chapter provides an overview of ActionScript 3.0, the newest and most revolutionary
version of ActionScript.
ActionScript is the programming language for the Flash Player run-time environment. It
enables interactivity, data handling, and much more in Flash content and applications.
ActionScript is executed by the ActionScript Virtual Machine, which is part of Flash Player.
ActionScript code is typically compiled into bytecode format by a compiler, such as the one
built into the Flash authoring tool or Flex Builder, or that is available in the Flex SDK and the
Flex Data Services. The bytecode is embedded in SWF files, which are executed by the Flash
Player, the run-time environment.
ActionScript 3.0 offers a robust programming model that will be familiar to developers with a
basic knowledge of object-oriented programming. Some of the key features of ActionScript
3.0 include the following:
■ A new ActionScript Virtual Machine, called AVM2, that uses a new bytecode instruction
set and provides significant performance improvements
■ A more modern compiler code base that adheres much more closely to the ECMAScript
(ECMA 262) standard and that performs deeper optimizations than previous versions of
the compiler
■ An expanded and improved application programming interface (API), with low-level
control of objects and a true object-oriented model
1
15
Page 16
■ A core language based on the upcoming ECMAScript (ECMA-262) edition 4 draft
language specification
■ An XML API based on ECMAScript for XML (E4X), as specified in ECMA-357 edition
2 specification. E4X is a language extension to ECMAScript that adds XML as a native
data type of the language.
■ An event model based on the Document Object Model (DOM) Level 3 Events
Specification
Advantages of ActionScript 3.0
ActionScript 3.0 goes beyond the scripting capabilities of previous versions of ActionScript. It
is designed to facilitate the creation of highly complex applications with large data sets and
object-oriented, reusable code bases. While ActionScript 3.0 is not required for content that
runs in Adobe Flash Player 9, it opens the door to performance improvements that are only
available with the AVM2, the new virtual machine. ActionScript 3.0 code can execute up to
ten times faster than legacy ActionScript code.
The older version of ActionScript Virtual Machine, AVM1, executes ActionScript 1.0 and
ActionScript 2.0 code. AVM1 is supported by Flash Player 9 for backward compatibility with
existing and legacy content. For more information, see “Compatibility with previous versions”
on page 20.
What’s new in ActionScript 3.0
Although ActionScript 3.0 contains many classes and features that will be familiar to
ActionScript programmers, ActionScript 3.0 is architecturally and conceptually different from
previous versions of ActionScript. The enhancements in ActionScript 3.0 include new
features of the core language and an improved Flash Player API that provides increased
control of low-level objects.
Core language features
The core language defines the basic building blocks of the programming language, such as
statements, expressions, conditions, loops, and types. ActionScript 3.0 contains many new
features that speed up the development process.
16Introduction to ActionScript 3.0
Page 17
Run-time exceptions
ActionScript 3.0 reports more error conditions than previous versions of ActionScript. Runtime exceptions are used for common error conditions, improving the debugging experience
and enabling you to develop applications that handle errors robustly. Run-time errors can
provide stack traces annotated with source file and line number information, helping you
quickly pinpoint errors.
Run-time types
In ActionScript 2.0, type annotations were primarily a developer aid; at run time, all values
were dynamically typed. In ActionScript 3.0, type information is preserved at run time, and
used for a number of purposes. Flash Player 9 performs run-time type checking, improving
the system’s type safety. Type information is also used to represent variables in native machine
representations, improving performance and reducing memory usage.
Sealed classes
ActionScript 3.0 introduces the concept of sealed classes. A sealed class possesses only the
fixed set of properties and methods that were defined at compile time; additional properties
and methods cannot be added. This enables stricter compile-time checking, resulting in more
robust programs. It also improves memory usage by not requiring an internal hash table for
each object instance. Dynamic classes are also possible using the
in ActionScript 3.0 are sealed by default, but can be declared to be dynamic with the
keyword.
dynamic keyword. All classes
dynamic
Method closures
ActionScript 3.0 enables a method closure to automatically remember its original object
instance. This feature is useful for event handling. In ActionScript 2.0, method closures
would not remember what object instance they were extracted from, leading to unexpected
behavior when the method closure was invoked. The mx.utils.Delegate class was a popular
workaround, but it is no longer needed.
What’s new in ActionScript 3.017
Page 18
ECMAScript for XML (E4X)
ActionScript 3.0 implements ECMAScript for XML (E4X), recently standardized as ECMA-
357. E4X offers a natural, fluent set of language constructs for manipulating XML. In
contrast to traditional XML-parsing APIs, XML with E4X performs like a native data type of
the language. E4X streamlines the development of applications that manipulate XML by
drastically reducing the amount of code needed. For more information about the ActionScript
3.0 implementation of E4X, see Chapter 11, “Working with XML,” on page 311.
To view ECMA’s E4X specification, go to www.ecma-international.org/publications/files/
ECMA-ST/ECMA-357.pdf .
Regular expressions
ActionScript 3.0 includes native support for regular expressions so that you can quickly search
for and manipulate strings. ActionScript 3.0 implements support for regular expressions as
they are defined in the ECMAScript edition 3 language specification (ECMA-262).
Namespaces
Namespaces are similar to the traditional access specifiers used to control visibility of
declarations (
can have names of your choice. Namespaces are outfitted with a Universal Resource Identifier
(URI) to avoid collisions, and are also used to represent XML namespaces when you work
with E4X.
public, private, protected). They work as custom access specifiers, which
New primitive types
ActionScript 2.0 has a single numeric type, Number, a double-precision, floating point
number. ActionScript 3.0 contains the int and uint types. The int type is a 32-bit signed
integer that lets ActionScript code take advantage of the fast integer math capabilities of the
CPU. The int type is useful for loop counters and variables where integers are used. The uint
type is an unsigned, 32-bit integer type that is useful for RGB color values, byte counts, and
more.
Flash Player API features
The Flash Player API in ActionScript 3.0 contains many new classes that allow you to control
objects at a low level. The architecture of the language is completely new and more intuitive.
While there are too many new classes to cover in detail here, the following sections highlight
some significant changes.
18Introduction to ActionScript 3.0
Page 19
DOM3 event model
Document Object Model Level 3 event model (DOM3) provides a standard way of
generating and handling event messages so that objects within applications can interact and
communicate, maintaining their state and responding to change. Patterned after the World
Wide Web Consortium DOM Level 3 Events Specification, this model provides a clearer and
more efficient mechanism than the event systems available in previous versions of
ActionScript.
Events and error events are located in the flash.events package. The Flex application
framework uses the same event model as the Flash Player API, so the event system is unified
across the Flash platform.
Display list API
The API for accessing the Flash Player display list—the tree that contains any visual elements
in a Flash application—consists of classes for working with visual primitives in Flash.
The new Sprite class is a lightweight building block, similar to MovieClip but more
appropriate as a base class for UI components. The new Shape class represents raw vector
shapes. These classes can be instantiated naturally with the
dynamically re-parented at any time.
Depth management is now automatic and built into Flash Player, rendering assignment of
depth numbers unnecessary. New methods are provided for specifying and managing the zorder of objects.
new operator and can be
Handling dynamic data and content
ActionScript 3.0 contains mechanisms for loading and handling assets and data in your Flash
application that are intuitive and consistent across the API. The new Loader class provides a
single mechanism for loading SWF files and image assets and provides a way to access detailed
information about loaded content. The URLLoader
loading text and binary data in data-driven applications. The Socket class provides a means to
read and write binary data to server sockets in any format.
class provides a separate mechanism for
What’s new in ActionScript 3.019
Page 20
Low-level data access
Various APIs provide low-level access to data that was never before available in ActionScript.
For data that is being downloaded, the URLStream class, which is implemented by
URLLoader, provides access to data as raw binary data while it is being downloaded. The
ByteArray class lets you optimize reading, writing, and working with binary data. The new
Sound API provides detailed control of sound through the SoundChannel and SoundMixer
classes. New APIs dealing with security provide information about the security privileges of a
SWF or loaded content, enabling you to better handle security errors.
Working with text
ActionScript 3.0 contains a flash.text package for all text-related APIs. The TextLineMetrics
class provides detailed metrics for a line of text within a text field; it replaces the
TextField.getLineMetrics() method in ActionScript 2.0. The TextField class contains a
number of interesting new low-level methods that can provide specific information about a
line of text or a single character in a text field. These methods include
getCharBoundaries(), which returns a rectangle representing the bounding box of a
character,
point, and
paragraph. Line-level methods include
characters in a specified line of text, and
specified line. A new Font class provides a means to manage embedded fonts in SWF files.
getCharIndexAtPoint(), which returns the index of the character at a specified
getFirstCharInParagraph(), which returns the index of the first character in a
getLineLength(), which returns the number of
getLineText(), which returns the text of the
Compatibility with previous versions
As always, Flash Player provides full backward compatibility with previously published
content. Any content that ran in previous versions of Flash Player runs in Flash Player 9. The
introduction of ActionScript 3.0 in Flash Player 9, however, does present some challenges for
interoperability between old and new content running in Flash Player 9. The compatibility
issues include the following:
■ A single SWF file cannot combine ActionScript 1.0 or 2.0 code with ActionScript 3.0
code.
■ ActionScript 3.0 code can load a SWF file written in ActionScript 1.0 or 2.0, but it
cannot access the SWF file’s variables and functions.
■ SWF files written in ActionScript 1.0 or 2.0 cannot load SWF files written in
ActionScript 3.0. This means that SWF files authored in Flash 8 or Flex Builder 1.5 or
earlier versions cannot load ActionScript 3.0 SWF files.
20Introduction to ActionScript 3.0
Page 21
The only exception to this rule is that an ActionScript 2.0 SWF file can replace itself with
an ActionScript 3.0 SWF file, as long as the ActionScript 2.0 SWF file hasn't previously
loaded anything into any of its levels. An ActionScript 2.0 SWF file can do this through a
call to
loadMovieNum(), passing a value of 0 to the level parameter.
■ In general, SWF files written in ActionScript 1.0 or 2.0 must be migrated if they are to
work together with SWF files written in ActionScript 3.0. For example, say you created a
media player using ActionScript 2.0. The media player loads various content that was also
created using ActionScript 2.0. You cannot create new content in ActionScript 3.0 and
load it in the media player. You must migrate the video player to ActionScript 3.0.
If, however, you create a media player in ActionScript 3.0, that media player can perform
simple loads of your ActionScript 2.0 content.
The following diagram summarizes the limitations of previous versions of Flash Player in
relation to loading new content and executing code, as well as the limitations for crossscripting between SWF files written in different versions of ActionScript.
Supported
Run-time environment
functionality
Flash Player 7Flash Player 8Flash Player 9
Can load SWFs
published for
Contains this AVM
Runs SWFs written in
ActionScript
Supported
7 and earlier8 and earlier9 and earlier
AVM1AVM1AVM1 and AVM2
1.0 and 2.01.0 and 2.01.0 and 2.0, and 3.0
Content created in
functionality*
ActionScript 1.0 and 2.0ActionScript 3.0
Can load content and
execute code in content
created in
Can cross script content
created in
* Content running in Flash Player 9 or later. Content running in Flash Player 8 or earlier can
load, display, execute, and cross-script only ActionScript 1.0 and 2.0.
†ActionScript 3.0 through Local Connection.
‡ActionScript 1.0 and 2.0 through LocalConnection.
ActionScript 1.0 and 2.0 onlyActionScript 1.0 and 2.0,
and ActionScript 3.0
ActionScript 1.0 and 2.0 only†
ActionScript 3.0‡
Compatibility with previous versions21
Page 22
22Introduction to ActionScript 3.0
Page 23
CHAPTER 2
Getting Started with
ActionScript
This chapter provides a no-frills, step-by-step approach to building a simple ActionScript 3.0
application.
The ActionScript 3.0 programming language can be used from within a number of different
development environments, including Macromedia Flash from Adobe and Adobe Flex
Builder 2. This chapter will show how to create modular ActionScript code that can be used
from within either of these application development environments.
No matter whether your ActionScript project is large or small, using a process to design and
develop your application will help you work more efficiently and effectively. Here are a set of
steps for a basic development process for building an application that uses ActionScript 3.0:
1. Design your application.
You should describe your application in some way before you start building it.
2. Compose your ActionScript 3.0 code.
You can create ActionScript code using Flash, Flex Builder, Macromedia Dreamweaver®
from Adobe, or a text editor.
23
Page 24
3. Create a Flash or Flex application file to run your code.
In the Flash authoring tool, this involves creating a new FLA file, setting up the publish
settings, adding user interface components to the application, and referencing the
ActionScript code. In the Flex development environment, creating a new application file
involves defining the application and adding user interface components using MXML,
and referencing the ActionScript code.
4. Publish and test your ActionScript application.
This involves running your application from within the Flash authoring or Flex
development environment, and making sure it does everything you intended.
Note that you don’t necessarily have to follow these steps in order, or completely finish one
step before working on another. For example, you might design one screen of your application
(step 1), then create the graphics, buttons, and so forth (step 3), before writing ActionScript
code (step 2) and testing (step 4). Or you might design part of it, then add one button or
interface element at a time, writing ActionScript for each one and testing it as it’s built. So
while it’s convenient to remember these four stages of the development process, in real-world
development it’s usually more effective to move back and forth among the stages as
appropriate.
Options for organizing your code
You can use ActionScript 3.0 code to power everything from simple graphics animations to
complex, client-server transaction processing systems. Depending on the type of application
you’re building, you may prefer to use one or more of these different ways of including
ActionScript in your project.
Storing code in frames in a Flash timeline
In the Flash authoring environment, you can add ActionScript code to any frame in a
timeline. This code will be executed while the movie is playing back, when the playhead
enters that frame.
Placing ActionScript code in frames provides a simple way to add behaviors to applications
built in the Flash authoring tool. You can add code to any frame in the main timeline or to
any frame in the timeline of any MovieClip symbol. However, this flexibility comes with a
cost. When you build larger applications, it becomes easy to lose track of which frames
contain which scripts, which can make the application more difficult to maintain over time.
24Getting Started with ActionScript
Page 25
Many developers simplify the organization of their ActionScript code in the Flash authoring
tool by placing code only in the first frame of a timeline, or on a specific layer in the Flash
document. This makes it easier to locate and maintain the code in your Flash FLA files.
However, in order to use the same code in another Flash or Flex project, you must copy and
paste the code into the new file.
If you want to be able to use your ActionScript code in other Flash or Flex projects in the
future, you will want to store your code in external ActionScript files (text files with the .as
extension).
Embedding code in Flex MXML files
In a Flex development environment, you can include ActionScript code inside an
<mx:Script> tag in a Flex MXML file. Inline ActionScript code like this has the same
drawback as code placed on a frame in Flash: you cannot reuse the code without cutting and
pasting it to a new source location.
NOTE
You can specify a source parameter for an <mx:Script> tag, which lets you insert
ActionScript code as if it was typed directly within the
source file that you use cannot define its own class, which limits its reusability.
<mx:Script> tag. However, the
Storing code in ActionScript files
If your project involves significant ActionScript code, the best way to organize your code is in
separate ActionScript source files (text files with the .as extension). An ActionScript file can be
structured in one of two ways, depending on how you intend to use it in your application:
■ Unstructured ActionScript code: lines of ActionScript code, including statements or
function definitions, written as though they were entered directly in a timeline script,
MXML file, etc.
ActionScript written in this way can be accessed using the
ActionScript, or the
<mx:Script> tag in Flex MXML. The ActionScript include
statement causes the contents of an external ActionScript file to be inserted at a specific
location and within a given scope in a script, as if it were entered there directly. In the Flex
MXML language, the
<mx:Script> tag lets you specify a source attribute that identifies
an external ActionScript file to be loaded at that point in the application. For example, the
following tag will load an external ActionScript file named Box.as:
<mx:Script source=“Box.as” />
include statement in
Options for organizing your code25
Page 26
■ ActionScript class definition: a definition of an ActionScript class, including its method
and property definitions.
When you define a class, you can access the ActionScript code in the class by creating an
instance of the class and using its properties, methods, and events, just as you would with
any of the built-in ActionScript classes. This requires two parts:
■Use the import statement to specify the full name of the class, so the ActionScript
compiler knows where to find it. For example, if you want to use the MovieClip class
in ActionScript, you first need to import that class using its full name, including
package and class:
import flash.display.MovieClip;
Alternatively, you can import the package that contains the MovieClip class, which is
equivalent to writing separate import statements for each class in the package:
import flash.display.*;
The only exceptions to the rule that a class must be imported in order to refer to that
class in your code are the top-level classes which are not defined in a package.
■Write code which specifically refers to the class name (usually declaring a variable with
that class as its data type, and creating an instance of the class to store in the variable).
By referring to another class name in ActionScript code, you tell the compiler to load
the definition of that class. For example, given an external class called Box, this
statement causes a new instance of the Box class to be created:
var smallBox:Box = new Box(10,20);
When the compiler comes across the reference to the Box class for the first time, it
searches the loaded source code to locate the Box class definition.
Example: Creating a basic application
You can create external ActionScript source files with an .as extension using Flash, Flex
Builder, Dreamweaver, or any text editor.
ActionScript 3.0 can be used within a number of application development environments,
including the Flash authoring and Flex Builder tools.
This section walks through the steps in creating and enhancing a simple ActionScript 3.0
application using the Flash authoring tool or the Flex Builder 2 tool. The application you’ll
build presents a simple pattern for using external ActionScript 3.0 class files in Flash and Flex
applications. That pattern will apply to all of the other example applications in this book.
26Getting Started with ActionScript
Page 27
Designing your ActionScript application
You should have some idea about the application you want to build before you start building it.
The representation of your design can be as simple as the name of the application and a brief
statement of its purpose, or as complicated as a set of requirements documents containing
numerous Unified Modeling Language (UML) diagrams. This book doesn’t discuss the
discipline of software design in detail, but it’s important to keep in mind that application
design is an essential step in the development of ActionScript applications.
Our first example of an ActionScript application will be a standard “Hello World”
application, so its design is very simple:
■ The application will be called HelloWorld.
■ It will display a single text field containing the words “Hello World!”
■ In order to be easily reused, it will use a single object-oriented class, named Greeter, which
can be used from within a Flash document or a Flex application.
■ After you create a basic version of the application, you will add new functionality to have
the user enter a user name and have the application check the name against a list of known
users.
With that concise definition in place, you can start building the application itself.
Creating the HelloWorld project and the Greeter class
The design statement for the Hello World application said that its code should be easy to
reuse. With this goal in mind, the application uses a single object-oriented class, named
Greeter, which is used from within an application that you create in Flex Builder or the Flash
authoring tool.
To create the HelloWorld project and Greeter class in Flex Builder:
1. In Flex Builder, select File > New> Flex Project,
2. If the New Flex Project dialog box asks you to select a Flex Server Technology, select Basic,
and then click Next.
3. Type HelloWorld as the Project Name, and then click Finish.
Your new project will be created and should be showing in the Navigator panel. By default
the project should already contain a file named HelloWorld.mxml, and that file should be
open in the Editor panel.
4. Now to create a custom ActionScript class file in the Flex Builder tool, select File > New >
ActionScript File.
Example: Creating a basic application27
Page 28
5. In the New ActionScript File dialog box, select HelloWorld as the parent folder, type
Greeter.as the filename, and then click Finish.
A new ActionScript editing window is displayed.
Continue with “Adding code to the Greeter class” on page 28.
Adding code to the Greeter class
The Greeter class defines an object, Greeter, that you will be able to use in your HelloWorld
application.
To add code to the Greeter class:
1. Type the following code into the new file:
package
{
public class Greeter
{
public function sayHello():String
{
var greeting:String;
greeting = "Hello World!";
return greeting;
}
}
}
The Greeter class includes a single sayHello() method, which returns a string that says
“Hello” to the user name that is given.
2. Select File > Save to save this ActionScript file.
The Greeter class is now ready to be used in a Flash or Flex application.
Creating an application that uses your ActionScript
code
The Greeter class that you have built defines a self-contained set of software functions, but it
does not represent a complete application. To use the class, you need to create a Flash
document or Flex application.
The HelloWorld application creates an new instance of the Greeter class. Here’s how to attach
the Greeter class to your application.
28Getting Started with ActionScript
Page 29
To create an ActionScript application using Flex Builder:
1. Open the HelloWorld.mxml file, and type the following code:
// says hello at the start, and asks for the user's name
mainTxt.text = myGreeter.sayHello();
}
]]>
</mx:Script>
<mx:TextArea id = "mainTxt" width="400" />
</mx:Application>
This Flex project includes three MXML tags:
■An <mx:Application> tag, which defines the Application container
■An <mx:Script> tag that includes some ActionScript code
■An <mx:TextArea> tag, which defines a field to display text messages to the user
The code in the
application loads. The
the “Hello World!” string returned by the
<mx:Script> tag defines a initApp() method that is called when the
initApp() method sets the text value of the mainTxt TextArea t o
sayHello() method of the custom class
Greeter, which you just wrote.
2. Select File > Save to save the application.
Continue with “Publishing and testing your ActionScript application” on page 30.
Example: Creating a basic application29
Page 30
Publishing and testing your ActionScript application
Software development is an iterative process. You write some code, try to compile it, and edit
the code until it compiles cleanly. You run the compiled application, test it to see if it fulfills
the intended design, and if it doesn’t, you edit the code again until it does. The Flash and Flex
Builder development environments offer a number of ways to publish, test, and debug your
applications.
Here are the basic steps for testing the HelloWorld application in each environment.
To publish and test an ActionScript application using Flex Builder:
1. Select Run > Run. Make sure that the Project field shows “HelloWorld” and the
Application file field shows “HelloWorld.mxml”.
2. In the Run dialog box, click Run.
The HelloWorld application starts.
■If any errors or warnings are displayed in the Output window when you test your
application, fix the causes of these errors in the HelloWorld.mxml or Greeter.as files,
and then try testing the application again.
■If there are no compilation errors, a browser window opens showing the Hello World
application. The text “Hello World!” should be displayed.
You have just created a simple but complete object-oriented application that uses ActionScript
3.0. Continue with “Enhancing the HelloWorld application” on page 30.
Enhancing the HelloWorld application
To make the application a little more interesting, you’ll now make it ask for and validate a user
name against a predefined list of names.
First, you will update the Greeter class to add new functionality. Then you will update the
Flex or Flash application to use the new functionality.
To update the Greeter.as file:
1. Open the Greeter.as file.
30Getting Started with ActionScript
Page 31
2. Change the contents of the file to the following (new and changed lines are shown in
boldface):
package
{
public class Greeter
{
/**
* Defines the names that should receive a proper greeting.
*/
public static var validNames:Array = ["Sammy", "Frank", "Dean"];
/**
* Builds a greeting string using the given name.
*/
public function sayHello(userName:String = ""):String
{
var greeting:String;
if (userName == "")
{
the Enter key.";
greeting = "Hello. Please type your user name, and then press
}
else if (validName(userName))
{
greeting = "Hello, " + userName + ".";
}
else
{
greeting = "Sorry, " + userName + ", you are not on the list.";
}
return greeting;
}
/**
* Checks whether a name is in the validNames list.
*/
public static function validName(inputName:String = ""):Boolean
{
if (validNames.indexOf(inputName) > -1)
{
return true;
}
else
{
return false;
}
}
}
}
Example: Creating a basic application31
Page 32
The Greeter class now has a number of new features:
■The validNames array lists valid user names. The array is initialized to a list of three
names when the Greeter class is loaded.
■The sayHello() method now accepts a user name and changes the greeting based on
some conditions. If the
to prompt the user for a name. If the user name is valid, the greeting becomes
userName.”
Finally, if either of those two conditions are not met, the greeting
variable is set to
■The validName() method returns true if the inputName is found in the validNames
array, and
false if it is not found. The statement validNames.indexOf(inputName)
checks each of the strings in the
Array.indexOf() method returns the index position of the first instance of an object
userName is an empty string (""), the greeting property is set
"Hello,
"Sorry, userName, you are not on the list."
validNames array against the inputName string. The
in an array, or the value -1 if the object is not found in the array.
Next you will edit the Flash or Flex file that references this ActionScript class.
To modify the application using Flex Builder:
1. Open the HelloWorld.mxml file.
2. Next modify the <mx:TextArea> tag to indicate to the user that is is for display only, by
changing the background color to a light gray and preventing the user from editing the
displayed text:
<mx:TextArea id = "mainTxt" width="400" backgroundColor="#DDDDDD"
editable="false" />
3.
Now add the following lines right after the <mx:TextArea> closing tag. These lines create
a new TextInput field that lets the user enter a user name value:
The enter attribute specifies that when the user presses the Enter key in the userNameTxt
field, the text in the field will be passed to the
greeting displayed in the
mainTxt field will change accordingly.
Greeter.sayHello() method, and the
The final contents of the HelloWorld.mxml file should look like this:
Save the edited HelloWorld.mxml file. Select File > Run to run the application.
When you run the application, you will be prompted to enter a user name. If it is valid
(Sammy, Frank, or Dean), the application will display the “
Hello, userName”
confirmation message.
Running subsequent examples
Having developed and run the “Hello World” ActionScript 3.0 application, you should have
the basic knowledge you need to run the other code examples presented in this book.
Subsequent code examples will not be presented in a step-by-step tutorial format as this one
was. The relevant ActionScript 3.0 code in each example will be highlighted and discussed,
but instructions about running the examples in specific development environments won’t be
provided. However the example files distributed with this book will include all of the files you
need to compile and run the examples easily in your chosen development environment.
Example: Creating a basic application33
Page 34
34Getting Started with ActionScript
Page 35
CHAPTER 3
ActionScript Language
and Syntax
ActionScript 3.0 comprises both the core ActionScript language and the Flash Player
Application Programming Interface (API). The core language is the part of ActionScript that
implements the draft ECMAScript (ECMA-262), Edition 4 draft language specification. The
Flash Player API provides programmatic access to Flash Player.
This chapter provides a brief introduction to the core ActionScript language and syntax. After
reading this chapter, you should have a basic understanding of how to work with data types
and variables, how to use proper syntax, and how to control the flow of data in your program.
Objects lie at the heart of the ActionScript 3.0 language—they are its fundamental building
blocks. Every variable you declare, every function you write, and every class instance you
create is an object. You can think of an ActionScript 3.0 program as a group of objects that
carry out tasks, respond to events, and communicate with one another.
35
Page 36
Programmers familiar with object-oriented programming (OOP) in Java or C++ may think of
objects as modules that contain two kinds of members: data stored in member variables or
properties, and behavior accessible through methods. The ECMAScript edition 4 draft, the
standard upon which ActionScript 3.0 is based, defines objects in a similar but slightly
different way. In the ECMAScript draft, objects are simply collections of properties. These
properties are containers that can hold not only data, but also functions or other objects. If a
function is attached to an object in this way, it is called a method.
While the ECMAScript draft definition may seem a little odd to programmers with a Java or
C++ background, in practice, defining object types with ActionScript 3.0 classes is very
similar to the way classes are defined in Java or C++. The distinction between the two
definitions of object is important when discussing the ActionScript object model and other
advanced topics, but in most other situations the term properties means class member variables
as opposed to methods. The ActionScript 3.0 Language Reference, for example, uses the term properties to mean variables or getter-setter properties. It uses the term methods to mean
functions that are part of a class.
One subtle difference between classes in ActionScript and classes in Java or C++ is that in
ActionScript, classes are not just abstract entities. ActionScript classes are represented by class objects that store the class’s properties and methods. This allows for techniques that may seem
alien to Java and C++ programmers, such as including statements or executable code at the
top level of a class or package.
Another difference between ActionScript classes and Java or C++ classes is that every
ActionScript class has something called a prototype object. In previous versions of ActionScript,
prototype objects, linked together into prototype chains, served collectively as the foundation
of the entire class inheritance hierarchy. In ActionScript 3.0, however, prototype objects play
only a small role in the inheritance system. The prototype object can still be useful, however,
as an alternative to static properties and methods if you want to share a property and its value
among all the instances of a class.
In the past, advanced ActionScript programmers could directly manipulate the prototype
chain with special built-in language elements. Now that the language provides a more mature
implementation of a class-based programming interface, many of these special language
elements, such as
__proto__ and __resolve, are no longer part of the language. Moreover,
optimizations of the internal inheritance mechanism that provide significant Flash Player
performance improvements preclude direct access to the inheritance mechanism.
36ActionScript Language and Syntax
Page 37
Objects and classes
In ActionScript 3.0, every object is defined by a class. A class can be thought of as a template
or a blueprint for a type of object. Class definitions can include variables and constants, which
hold data values, and methods, which are functions that encapsulate behavior bound to the
class. The values stored in properties can be primitive values or other objects. Primitive values
are numbers, strings, or Boolean values.
ActionScript contains a number of built-in classes that are part of the core language. Some of
these built-in classes, such as Number, Boolean and String, represent the primitive values
available in ActionScript. Others, such as the Array, Math, and XML classes, define more
complex objects that are part of the ECMAScript standard.
All classes, whether built-in or user-defined, derive from the Object class. For programmers
with previous ActionScript experience, it is important to note that the Object data type is no
longer the default data type, even though all other classes still derive from it. In ActionScript
2.0, the following two lines of code were equivalent because the lack of a type annotation
meant that a variable would be of type Object:
var someObj:Object;
var someObj;
ActionScript 3.0, however, introduces the concept of untyped variables, which can be
designated in the following two ways:
var someObj:*;
var someObj;
An untyped variable is not the same as a variable of type Object. The key difference is that
untyped variables can hold the special value
cannot hold that value.
You can define your own classes using the
three ways: constants can be defined with the
var keyword, and getter and setter properties are defined by using the get and set attributes
in a method declaration. You can declare methods with the
You create an instance of a class by using the
instance of the Date class called
var myBirthday:Date = new Date();
myBirthday.
undefined, while a variable of type Object
class keyword. You can declare class properties in
const keyword, variables are defined with the
function keyword.
new operator. The following example creates an
Objects and classes37
Page 38
Packages and namespaces
Packages and namespaces are related concepts. Packages allow you to bundle class definitions
together in a way that facilitates code sharing and minimizes naming conflicts. Namespaces
allow you to control the visibility of identifiers, such as property and method names, and can
be applied to code whether it resides inside or outside a package. Packages let you organize
your class files, and namespaces let you manage the visibility of individual properties and
methods.
Packages
Packages in ActionScript 3.0 are implemented with namespaces, but are not synonymous with
them. When you declare a package, you are implicitly creating a special type of namespace
that is guaranteed to be known at compile time. Namespaces, when created explicitly, are not
necessarily known at compile time.
The following example uses the
class:
package samples
{
public class SampleCode
{
public var sampleGreeting:String;
public function sampleFunction()
{
trace(sampleGreeting + " from sampleFunction()");
}
}
}
The name of the class in this example is SampleCode. Because the class is inside the samples
package, the compiler automatically qualifies the class name at compile time into its fully
qualified name: samples.SampleCode. The compiler also qualifies the names of any properties
or methods, so that
samples.SampleCode.sampleGreeting and samples.SampleCode.sampleFunction(),
sampleGreeting and sampleFunction() become
respectively.
package directive to create a simple package containing one
38ActionScript Language and Syntax
Page 39
Many developers, especially those with Java programming backgrounds, may choose to place
only classes at the top level of a package. ActionScript 3.0, however, supports not only classes
at the top level of a package, but also variables, functions, and even statements. One advanced
use of this feature is to define a namespace at the top level of a package so that it will be
available to all classes in that package. Note, however, that only two access specifiers,
and
internal, are allowed at the top level of a package. Unlike Java, which allows you to
In many other ways, however, ActionScript 3.0 packages are similar to packages in the Java
programming language. As you can see in the previous example, fully qualified package
references are expressed using the dot operator (
.), just as they are in Java. You can use
packages to organize your code into an intuitive hierarchical structure for use by other
programmers. This facilitates code sharing by allowing you to create your own package to
share with others, and to use packages created by others in your code.
The use of packages also helps to ensure that the identifier names that you use are unique and
do not conflict with other identifier names. In fact, some would argue that this is the primary
benefit of packages. For example, two programmers who wish to share their code with each
other may have each created a class called SampleCode. Without packages, this would create a
name conflict, and the only resolution would be to rename one of the classes. With packages,
however, the name conflict is easily avoided by placing one, or preferably both, of the classes
in packages with unique names.
You can also include embedded dots in your package name to create nested packages. This
allows you to create a hierarchical organization of packages. A good example of this is the
flash.xml package provided by the Flash Player API. The flash.xml package is nested inside the
flash package.
The flash.xml package contains the legacy XML parser that was used in previous versions of
ActionScript. One reason that it now resides in the flash.xml package is that the name of the
legacy XML class conflicts with the name of the new XML class that implements the XML for
ECMAScript (E4X) specification functionality available in ActionScript 3.0.
Although moving the legacy XML class into a package is a good first step, most users of the
legacy XML classes will import the flash.xml package, which will generate the same name
conflict unless you remember to always use the fully qualified name of the legacy XML class
(flash.xml.XML). To avoid this situation, the legacy XML class is now named
XMLDocument, as the following example shows:
package flash.xml
{
class XMLDocument {}
class XMLNode {}
class XMLSocket {}
}
Packages and namespaces39
Page 40
Most of the Flash Player API is organized under the flash package. For example, the
flash.display package contains the display list API, and the flash.events package contains the
new event model. A detailed discussion of the Flash Player API packages can be found in Part
3 of this book. For more information, see “Flash Player APIs” on page 335.
Creating packages
ActionScript 3.0 provides significant flexibility in the way you organize your packages, classes,
and source files. Previous versions of ActionScript allowed only one class per source file and
required that the name of the source file match the name of the class. ActionScript 3.0 allows
you to include multiple classes in one source file, but only one class in each file can be made
available to code that is external to that file. In other words, only one class in each file can be
declared inside a package declaration. You must declare any additional classes outside your
package definition, which makes those classes invisible to code outside that source file. The
name of the class declared inside the package definition must match the name of the source file.
ActionScript 3.0 also provides more flexibility in the way you declare packages. In previous
versions of ActionScript, packages merely represented directories in which you placed source
files, and you didn’t declare packages with the
package name as part of the fully qualified class name in your class declaration. Although
packages still represent directories in ActionScript 3.0, packages can contain more than just
classes. In ActionScript 3.0, you use the
that you can also declare variables, functions, and namespaces at the top level of a package.
You can even include executable statements at the top level of a package. If you do declare
variables, functions, or namespaces at the top level of a package, the only attributes available
at that level are
the
public attribute, whether that declaration is a class, variable, function, or namespace.
public and internal, and only one package-level declaration per file can use
Packages are useful for organizing your code and for preventing name conflicts. You should
not confuse the concept of packages with the unrelated concept of class inheritance. Two
classes that reside in the same package will have a namespace in common, but are not
necessarily related to each other in any other way. Likewise, a nested package may have no
semantic relationship to its parent package.
package statement, but rather included the
package statement to declare a package, which means
40ActionScript Language and Syntax
Page 41
Importing packages
If you want to use a class that is inside a package, you must import either the package or the
specific class. This differs from ActionScript 2.0, where importing classes was optional.
For example, consider the SampleCode class example from earlier in this chapter. If the class
resides in a package named samples, you must use one of the following import statements
before using the SampleCode class:
import samples.*;
or
import samples.SampleCode;
In general, import statements should be as specific as possible. If you plan to use only the
SampleCode class from the samples
rather than the entire package to which it belongs. Importing entire packages may lead to
unexpected name conflicts.
You must also place the source code that defines the package or class within your classpath.
The classpath is a user-defined list of local directory paths that determines where the compiler
will search for imported packages and classes. The classpath is sometimes called the build path
or source path.
After you have properly imported the class or package, you can use either the fully qualified
name of the class (samples.SampleCode) or merely the class name by itself (SampleCode).
Fully qualified names are useful when identically named classes, methods, or properties result
in ambiguous code, but can be difficult to manage if used for all identifiers. For example, the
use of the fully qualified name results in verbose code when you instantiate a SampleCode
class instance:
var mySample:samples.SampleCode = new samples.SampleCode();
As the levels of nested packages increase, the readability of your code decreases. In situations
where you are confident that ambiguous identifiers will not be a problem, you can make your
code easier to read by using simple identifiers. For example, instantiating a new instance of the
SampleCode class is much less verbose if you use only the class identifier:
var mySample:SampleCode = new SampleCode();
If you attempt to use identifier names without first importing the appropriate package or
class, the compiler will not be able to find the class definitions. On the other hand, if you do
import a package or class, any attempt to define a name that conflicts with an imported name
will generate an error.
package, you should import only the SampleCode class
Packages and namespaces41
Page 42
When a package is created, the default access specifier for all members of that package is
internal, which means that, by default, package members are only visible to other members
of that package. If you want a class to be available to code outside the package, you must
declare that class to be
public. For example, the following package contains two classes,
SampleCode and CodeFormatter:
// SampleCode.as file
package samples
{
public class SampleCode {}
}
// CodeFormatter.as file
package samples
{
class CodeFormatter {}
}
The SampleCode class is visible outside the package because it is declared as a public class.
The CodeFormatter class, however, is visible only within the samples package itself. If you
attempt to access the CodeFormatter class outside the samples package, you will generate an
error, as the following example shows:
import samples.SampleCode;
import samples.CodeFormatter;
var mySample:SampleCode = new SampleCode(); // okay, public class
var myFormatter:CodeFormatter = new CodeFormatter(); // error
If you want both classes to be available outside the package, you must declare both classes to
be
public. You cannot apply the public attribute to the package declaration.
Fully qualified names are useful for resolving name conflicts that may occur when using
packages. Such a scenario may arise if you import two packages that define classes with the
same identifier. For example, consider the following package, which also has a class named
SampleCode:
package langref.samples
{
public class SampleCode {}
}
If you import both classes, as follows, you will have a name conflict when referring to the
SampleCode class:
import samples.SampleCode;
import langref.samples.SampleCode;
var mySample:SampleCode = new SampleCode(); // name conflict
42ActionScript Language and Syntax
Page 43
The compiler has no way of knowing which SampleCode class to use. To resolve this conflict,
you must use the fully qualified name of each class, as follows:
var sample1:samples.SampleCode = new samples.SampleCode();
var sample2:langref.samples.SampleCode = new langref.samples.SampleCode();
NOTE
Programmers with a C++ background often confuse the import statement with
#include. The #include directive is necessary in C++ because C++ compilers process
one file at a time, and will not look in other files for class definitions unless a header file is
explicitly included. ActionScript 3.0 has an include directive, but it is not designed to
import classes and packages. To import classes or packages in ActionScript 3.0, you
must use the import statement and place the source file that contains the package in
the class path.
Namespaces
Namespaces give you control over the visibility of the properties and methods that you create.
Think of the
in namespaces. If these predefined access control specifiers do not suit your needs, you can
create your own namespaces.
If you are familiar with XML namespaces, much of this discussion will not be new to you,
although the syntax and details of the ActionScript implementation are slightly different from
those of XML. If you have never worked with namespaces before, the concept itself is
straightforward, but the implementation has specific terminology that you will need to learn.
To understand how namespaces work, it helps to know that the name of a property or method
always contains two parts: an identifier and a namespace. The identifier is what you generally
think of as a name. For example, the identifiers in the following class definition are
sampleGreeting and sampleFunction():
class SampleCode
{
var sampleGreeting:String;
function sampleFunction () {
}
}
Whenever definitions are not preceded by a namespace attribute, their names are qualified by
the default
package. If the compiler is set to strict mode, the compiler issues a warning that the
namespace applies to any identifier without a namespace attribute. To ensure that an
identifier is available everywhere, you must specifically precede the identifier name with the
public attribute. In the previous example code, both sampleGreeting and
sampleFunction() have a namespace value of internal.
public, private, protected, and internal access control specifiers as built-
trace(sampleGreeting + " from sampleFunction()");
internal namespace, which means they are visible only to callers in the same
internal
Packages and namespaces43
Page 44
There are three basic steps to follow when using namespaces. First, you must define the
namespace using the
version1 namespace:
namespace version1;
namespace keyword. For example, the following code defines the
Second, you apply your namespace by using it instead of an access control specifier in a
property or method declaration. The following example places a function named
myFunction() into the version1 namespace:
version1 function myFunction() {}
Third, once you’ve applied the namespace, you can reference it with the use directive or by
qualifying the name of an identifier with a namespace. The following example references the
myFunction() function through the use directive:
use namespace version1;
myFunction();
You can also use a qualified name to reference the myFunction() function, as the following
example shows:
version1::myFunction();
Defining namespaces
Namespaces contain one value, the Uniform Resource Identifier (URI), which is sometimes
called the namespace name. A URI allows you to ensure that your namespace definition is
unique.
You create a namespace by declaring a namespace definition in one of two ways. You can
either define a namespace with an explicit URI, as you would define an XML namespace, or
you can omit the URI. The following example shows how a namespace can be defined using a
URI:
The URI serves as a unique identification string for that namespace. If you omit the URI, as
in the following example, the compiler will create an unique internal identification string in
place of the URI. You do not have access to this internal identification string.
namespace flash_proxy;
Once you define a namespace, with or without a URI, that namespace cannot be redefined in
the same scope. An attempt to define a namespace that has been defined earlier in the same
scope results in a compiler error.
44ActionScript Language and Syntax
Page 45
If a namespace is defined within a package or a class, the namespace may not be visible to code
outside that package or class unless the appropriate access control specifier is used. For
example, the following code shows the
flash_proxy namespace defined within the flash.utils
package. In the following example, the lack of an access control specifier means that the
flash_proxy namespace would be visible only to code within the flash.utils package and
would not be visible to any code outside the package:
package flash.utils
{
namespace flash_proxy;
}
The following code uses the public attribute to make the flash_proxy namespace visible to
code outside the package:
package flash.utils
{
public namespace flash_proxy;
}
Applying namespaces
Applying a namespace means placing a definition into a namespace. Definitions that can be
placed into namespaces include functions, variables, and constants (you cannot place a class
into a custom namespace).
Consider, for example, a function declared using the
the
public attribute in a function definition places the function into the public namespace,
which makes the function available to all code. Once you have defined a namespace, you can
use the namespace that you defined the same way you would use the
the definition will be available to code that can reference your custom namespace. For
example, if you define a namespace
example1, you can add a method called myFunction()
using example1 as an attribute, as the following example shows:
namespace example1;
class someClass
{
example1 myFunction() {}
}
Declaring the myFunction() method using the namespace example1 as an attribute means
that the method belongs to the
example1 namespace.
public access control namespace. Using
public attribute, and
Packages and namespaces45
Page 46
You should bear in mind the following when applying namespaces:
■ You can apply only one namespace to each declaration.
■ There is no way to apply a namespace attribute to more than one definition at a time. In
other words, if you want to apply your namespace to ten different functions, you must
add your namespace as an attribute to each of the ten function definitions.
■ If you apply a namespace, you cannot also specify an access control specifier because
namespaces and access control specifiers are mutually exclusive. In other words, you
cannot declare a function or property as
public, private, protected, or internal in
addition to applying your namespace.
Referencing namespaces
There is no need to explicitly reference a namespace when you use a method or property
declared with any of the access control namespaces, such as
and
internal. This is because access to these special namespaces is controlled by context. For
example, definitions placed into the
private namespace are automatically available to code
within the same class. For namespaces that you define, however, such context sensitivity does
not exist. In order to use a method or property that you have placed into a custom namespace,
you must reference the namespace.
You can reference namespaces with the
with the namespace using the name qualifier (
the
use namespace directive “opens” the namespace, so that it can apply to any identifiers
use namespace directive or you can qualify the name
::) punctuator. Referencing a namespace with
that are not qualified. For example, if you have defined the
access names in that namespace by using
use namespace example1;
myFunction();
use namespace example1:
You can open more than one namespace at a time. Once you open a namespace with use
namespace
, it remains open throughout the block of code in which it was opened. There is no
way to explicitly close a namespace.
Having more than one open namespace, however, increases the likelihood of name conflicts.
If you prefer not to open a namespace, you can avoid the
qualifying the method or property name with the namespace and the name qualifier
punctuator. For example, the following code shows how you can qualify the name
myFunction() with the example1 namespace:
example1::myFunction();
public, private, protected,
example1 namespace, you can
use namespace directive by
46ActionScript Language and Syntax
Page 47
Using namespaces
You can find a real-world example of a namespace that is used to prevent name conflicts in the
flash.utils.Proxy class that is part of the Flash Player API. The Proxy class, which is the
replacement for the
intercept references to undefined properties or methods before an error occurs. All of the
methods of the Proxy class reside in the
conflicts.
To better understand how the
to use the Proxy class. The functionality of the Proxy class is available only to classes that
inherit from it. In other words, if you want to use the methods of the Proxy class on an object,
the object’s class definition must extend the Proxy class. For example, if you want to intercept
attempts to call an undefined method, you would extend the Proxy class and then override the
callProperty() method of the Proxy class.
You may recall that implementing namespaces is usually a three-step process of defining,
applying, and then referencing a namespace. Because you never explicitly call any of the Proxy
class methods, however, the
referenced. The Flash Player API defines the
Proxy class. Your code only needs to apply the
the Proxy class.
The
flash_proxy namespace is defined in the flash.utils package in a manner similar to the
following:
package flash.utils
{
public namespace flash_proxy;
}
The namespace is applied to the methods of the Proxy class as shown in the following excerpt
from the Proxy class:
public class Proxy
{
flash_proxy function callProperty(name:*, ... rest):*
flash_proxy function deleteProperty(name:*):Boolean
...
}
As the following code shows, you must first import both the Proxy class and the flash_proxy
namespace. You must then declare your class such that it extends the Proxy class (you must
also add the
callProperty() method, you must use the flash_proxy namespace.
package
{
Object.__resolve property from ActionScript 2.0, allows you to
flash_proxy namespace in order to prevent name
flash_proxy namespace is used, you need to understand how
flash_proxy namespace is only defined and applied, but never
flash_proxy namespace and applies it in the
flash_proxy namespace to classes that extend
dynamic attribute if you are compiling in strict mode). When you override the
flash_proxy override function callProperty(name:*, ...rest):*
{
trace("method call intercepted: " + name);
}
}
}
If you create an instance of the MyProxy class and call an undefined method, such as the
testing() method called in the following example, your Proxy object intercepts the method
call and executes the statements inside the overridden
a simple
var mySample:MyProxy = new MyProxy();
mySample.testing(); // method call intercepted: testing
trace() statement).
callProperty() method (in this case,
There are two advantages to having the methods of the Proxy class inside the flash_proxy
namespace. First, having a separate namespace reduces clutter in the public interface of any
class that extends the Proxy class. (There are about a dozen methods in the Proxy class that
you can override, all of which are not designed to be called directly. Placing all of them in the
public namespace could be confusing.) Second, use of the
flash_proxy namespace avoids
name conflicts in case your Proxy subclass contains instance methods with names that match
any of the Proxy class methods. For example, you may want to name one of your own
methods
callProperty() method is in a different namespace:
dynamic class MyProxy extends Proxy
{
}
callProperty(). The following code is acceptable because your version of the
public function callProperty() {}
flash_proxy override function callProperty(name:*, ...rest):*
{
trace("method call intercepted: " + name);
}
Namespaces can also be helpful when you want to provide access to methods or properties in
a way that cannot be accomplished with the four access control specifiers (
internal, and protected). For example, you may have a few utility methods that are spread
public, private,
out across several packages. You want these methods available to all of your packages, but you
don’t want the methods to be public. To accomplish this, you can create a new namespace and
use it as your own special access control specifier.
48ActionScript Language and Syntax
Page 49
The following example uses a user-defined namespace to group together two functions that
reside in different packages. By grouping them into the same namespace, you can make both
functions visible to a class or package through a single
use namespace statement.
This example uses four files to demonstrate the technique. All of the files must be within your
classpath. The first file, myInternal.as, is used to define the
myInternal namespace. Because
the file is in a package named example, you must place the file into a folder named example.
The namespace is marked as
// myInternal.as in folder example
package example
{
public namespace myInternal = "http://www.adobe.com/2006/actionscript/
examples";
}
public so that it can be imported into other packages.
The second and third files, Utility.as and Helper.as, define the classes that contain methods
that should be available to other packages. The Utility class is in the example.alpha package,
which means that the file should be placed inside a folder named alpha that is a subfolder of
the example folder. The Helper class is in the example.beta package, which means that the file
should be placed inside a folder named beta that is also a subfolder of the example folder.
Both of these packages, example.alpha and example.beta, must import the namespace before
using it.
// Utility.as in the example/alpha folder
package example.alpha
{
import example.myInternal;
use namespace myInternal;
public class Utility
{
private static var _taskCounter:int = 0;
public static function someTask()
{
_taskCounter++;
}
myInternal static function get taskCounter():int
{
return _taskCounter;
}
}
}
// Helper.as in the example/beta folder
package example.beta
{
Packages and namespaces49
Page 50
import example.myInternal;
use namespace myInternal;
public class Helper
{
private static var _timeStamp:Date;
public static function someTask()
{
_timeStamp = new Date();
}
myInternal static function get lastCalled():Date
{
return _timeStamp;
}
}
}
The fourth file, NamespaceUseCase.as, is the main application class, and should be a sibling
to the example folder. The NamespaceUseCase class will also import the
myInternal
namespace and use it to call the two static methods that reside in the other packages. The
example uses static methods only to simplify the code. Both static and instance methods can
be placed in the
// NamespaceUseCase.as
package
{
import flash.display.MovieClip;
import example.myInternal; // import namespace
import example.alpha.Utility; // import Utility class
import example.beta.Helper; // import Helper class
Helper.someTask();
trace(Helper.lastCalled); // [time someTask() last called]
}
}
}
50ActionScript Language and Syntax
Page 51
Variables
Variables allow you to store values that you use in your program. To declare a variable, you
must use the
statement is only required if you use type annotations. In ActionScript 3.0, use of the
statement is always required. For example, the following line of ActionScript declares a
variable named
var i;
If you omit the var statement when declaring a variable, you will get a compiler error in strict
mode and run-time error in standard mode. For example, the following line of code will result
in an error if the variable
i; // error if i was not previously defined
To associate a variable with a data type, you must do so when you declare the variable.
Declaring a variable without designating the variable’s type is legal, but will generate a
compiler warning in strict mode. You designate a variable’s type by appending the variable
name with a colon (:), followed by the variable’s type. For example, the following code
declares a variable
var i:int;
You can assign a value to a variable using the assignment operator (=). For example, the
following code declares a variable
var i:int;
i = 20;
You may find it more convenient to assign a value to a variable at the same time that you
declare the variable, as in the following example:
var i:int = 20;
The technique of assigning a value to a variable at the time it is declared is commonly used
not only when assigning primitive values such as integers and strings, but also when creating
an array or instantiating an instance of a class. The following example shows an array that is
declared and assigned a value using one line of code.
var numArray:Array = ["zero", "one", "two"];
You can create an instance of a class by using the new operator. The following example creates
an instance of a named
instance to the variable named
var customItem:CustomClass = new CustomClass();
var statement with the variable name. In ActionScript 2.0, use of the var
var
i:
i has not been previously defined:
i that is of type int:
i and assigns the value 20 to it:
CustomClass, and assigns a reference to the newly created class
customItem:
Variables51
Page 52
If you have more than one variable to declare, you can declare them all on one line of code by
using the comma operator (
,) to separate the variables. For example, the following code
declares three variables on one line of code:
var a:int, b:int, c:int;
You can also assign values to each of the variables on the same line of code. For example, the
following code declares three variables (
var a:int = 10, b:int = 20, c:int = 30;
a, b, and c) and assigns each a value:
Although you can use the comma operator to group variable declarations into one statement,
doing so may reduce the readability of your code.
Understanding variable scope
The scope of a variable is the area of your code where the variable can be accessed by a lexical
reference. A global variable is one that is defined in all areas of your code, whereas a local
variable is one that is defined in only one part of your code. In ActionScript 3.0, variables are
always scoped to the function or class in which they are declared. A global variable is a variable
that you define outside of any function or class definition. For example, the following code
creates a global variable
shows that a global variable is available both inside and outside the function definition.
var strGlobal:String = "Global";
function scopeTest ()
{
trace(strGlobal); // Global
}
scopeTest();
trace(strGlobal); // Global
You declare a local variable by declaring the variable inside a function definition. The smallest
area of code for which you can define a local variable is a function definition. A local variable
declared within a function will exist only in that function. For example, if you declare a
variable named
str2 within a function named localScope(), that variable will not be
available outside the function.
function localScope()
{
var strLocal:String = "local";
}
localScope();
trace(strLocal); // error because strLocal is not defined globally
strGlobal by declaring it outside of any function. The example
52ActionScript Language and Syntax
Page 53
If the variable name you use for your local variable is already declared as a global variable, the
local definition hides (or shadows) the global definition while the local variable is in scope.
The global variable will still exist outside of the function. For example, the following code
creates a global string variable named
inside the
value of the variable, but the
scopeTest() function. The trace statement inside the function outputs the local
trace statement outside the function outputs the global value of
str1, and then creates a local variable of the same name
the variable.
var str1:String = "Global";
function scopeTest ()
{
var str1:String = "Local";
trace(str1); // Local
}
scopeTest();
trace(str1); // Global
ActionScript variables, unlike variables in C++ and Java, do not have block-level scope. A
block of code is any group of statements between an opening curly brace (
curly brace (
} ). In some programming languages, such as C++ and Java, variables declared
{ ) and a closing
inside a block of code are not available outside that block of code. This restriction of scope is
called block-level scope, and does not exist in ActionScript. If you declare a variable inside a
block of code, that variable will be available not only in that block of code, but also in any
other parts of the function to which the code block belongs. For example, the following
function contains variables that are defined in various block scopes. All the variables are
available throughout the function.
function blockTest (testArray:Array)
{
var numElements:int = testArray.length;
if (numElements > 0)
{
var elemStr:String = "Element #";
for (var i:int = 0; i < numElements; i++)
{
var valueStr:String = i + ": " + testArray[i];
trace(elemStr + valueStr);
}
trace(elemStr, valueStr, i); // all still defined
}
trace(elemStr, valueStr, i); // all defined if numElements > 0
}
blockTest(["Earth", "Moon", "Sun"]);
Variables53
Page 54
An interesting implication of the lack of block-level scope is that you can read or write to a
variable before it is declared, as long as it is declared before the function ends. This is because
of a technique called hoisting, which means that the compiler moves all variable declarations
to the top of the function. For example, the following code compiles even though the initial
trace() function for the num variable happens before the num variable is declared:
trace(num); // NaN
var num:Number = 10;
trace(num); // 10
The compiler will not, however, hoist any assignment statements. This explains why the
initial
trace() of num results in NaN (not a number), which is the default value for variables
of the Number data type. This means that you can assign values to variables even before they
are declared, as shown in the following example:
num = 5;
trace(num); // 5
var num:Number = 10;
trace(num); // 10
Default values
A default value is the value that a variable contains before you set its value. You initialize a
variable when you set its value for the first time. If you declare a variable, but do not set its
value, that variable is uninitialized. The value of an uninitialized variable depends on its data
type. The following table describes the default values of variables, organized by data type:
Data typeDefault value
Boolean
int0
Number
Object
String
uint0
Not declared (equivalent to type annotation
All other classes, including user-defined classes.
For variables of type Number, the default value is
*)
NaN (not a number), which is a special value
false
NaN
null
null
undefined
null
defined by the IEEE-754 standard to mean a value that does not represent a number.
54ActionScript Language and Syntax
Page 55
If you declare a variable, but do not declare its data type, the default data type * will apply,
which actually means that the variable is untyped. If you also do not initialize an untyped
variable with a value, its default value is
undefined.
For data types other than Boolean, Number, int, and uint, the default value of any
uninitialized variable is
null. This applies to all the classes defined by the Flash Player API, as
well as any custom classes that you create.
The value
attempt to assign a value of
value for that data type. For variables of type Object, you can assign a value of
attempt to assign the value
null.
For variables of type Number, there is a special top-level function named
the Boolean value
null is not a valid value for variables of type Boolean, Number, int, or uint. If you
null to a such a variable, the value is converted to the default
null. If you
undefined to a variable of type Object, the value is converted to
isNaN() that returns
true if the variable is not a number, and false otherwise.
Data types
A data type defines a set of values. For example, the Boolean data type is the set of exactly two
values:
true and false. In addition to the Boolean data type, ActionScript 3.0 defines several
more commonly used data types, such as String, Number, and Array. You can define your own
data types by using classes or interfaces to define a custom set of values. All values in
ActionScript 3.0, whether they are primitive or complex, are objects.
A primitive value is a value that belongs to one of the following data types: Boolean, int,
Number, String, and uint. Working with primitive values is usually faster than working with
complex values because ActionScript stores primitive values in a special way that makes
memory and speed optimizations possible.
NOTE
For readers interested in the technical details, ActionScript stores primitive values internally
as immutable objects. The fact that they are stored as immutable objects means that
passing by reference is effectively the same as passing by value. This cuts down on memory
usage and increases execution speed because references are usually significantly smaller
than the values themselves.
A complex value is a value that is not a primitive value. Data types that define sets of complex
values include Array, Date, Error, Function, RegExp, XML, and XMLList.
Data types55
Page 56
Many programming languages distinguish between primitive values and their wrapper
objects. Java, for example, has an int primitive and the java.lang.Integer class that wraps it.
Java primitives are not objects, but their wrappers are, which makes primitives useful for some
operations and wrapper objects better suited for other operations. In ActionScript 3.0,
primitive values and their wrapper objects are, for practical purposes, indistinguishable. All
values, even primitive values, are objects. Flash Player treats these primitive types as special
cases that behave like objects but that don’t require the normal overhead associated with
creating objects. This means that the following two lines of code are equivalent:
var someInt:int = 3;
var someInt:int = new int(3);
All the primitive and complex data types listed above are defined by the ActionScript 3.0 core
classes. The core classes allow you to create objects using literal values instead of using the
new
operator. For example, you can create an array using a literal value or the Array class
constructor, as follows:
var someArray:Array = [1, 2, 3]; // literal value
var someArray:Array = new Array(1,2,3); // Array constructor
Type checking
Type checking can occur at either compile time or run time. Statically typed languages, such
as C++ and Java, do type checking at compile time. Dynamically typed languages, such as
Smalltalk and Python, handle type checking at run time. As a dynamically typed language,
ActionScript 3.0 has run-time type checking, but also supports compile-time type checking
with a special compiler mode called strict mode. In strict mode, type checking occurs at both
compile time and run time, but in standard mode, type checking occurs only at run time.
Dynamically typed languages offer tremendous flexibility when you structure your code, but
at the cost of allowing type errors to manifest at run time. Statically typed languages report
type errors at compile time, but at the cost of requiring type information to be known at
compile time.
Compile-time type checking
Compile-time type checking is often favored in larger projects because as the size of a project
grows, data type flexibility usually becomes less important than catching type errors as early as
possible. This is why, by default, the ActionScript compiler in Adobe Flash CS3 and Adobe
Flex Builder 2 is set to run in strict mode. You can disable strict mode in Flex Builder 2
through the ActionScript compiler settings in the Project Properties dialog box.
56ActionScript Language and Syntax
Page 57
In order to provide compile-time type checking, the compiler needs to know the data type
information for the variables or expressions in your code. To explicitly declare a data type for a
variable, add the colon operator (
:) followed by the data type as a suffix to the variable name.
To associate a data type with a parameter, you use the colon operator followed by the data
type. For example, the following code adds data type information to the
and declares a variable
function runtimeTest(xParam:String)
{
trace(xParam);
}
var myParam:String = “hello”;
runtimeTest(myParam);
myParam with an explicit data type:
xParam parameter,
In strict mode, the ActionScript compiler reports type mismatches as compiler errors. For
example, the following code declares a function parameter
xParam, of type Object, but later
attempts to assign values of type String and Number to that parameter. This produces a
compiler error in strict mode.
function dynamicTest(xParam:Object)
{
if (xParam is String)
{
var myStr:String = xParam; // compiler error in strict mode
trace("String: " + myStr);
}
else if (xParam is Number)
{
var myNum:Number = xParam; // compiler error in strict mode
trace("Number: " + myNum);
}
}
Even in strict mode, however, you can selectively opt of out compile-time type checking by
leaving the right side of an assignment statement untyped. You can mark a variable or
expression as untyped by either omitting a type annotation, or using the special asterisk (
type annotation. For example, if the
xParam parameter in the previous example is modified so
*)
that it no longer has a type annotation, the code will compile in strict mode:
function dynamicTest(xParam)
{
if (xParam is String)
{
var myStr:String = xParam;
trace("String: " + myStr);
}
else if (xParam is Number)
{
var myNum:Number = xParam;
Data types57
Page 58
trace("Number: " + myNum);
}
}
dynamicTest(100)
dynamicTest("one hundred");
Run-time type checking
Run-time type checking occurs in ActionScript 3.0 whether you compile in strict mode or
standard mode. Consider a situation in which the value 3 is passed as an argument to a
function that expects an array. In strict mode, the compiler will generate an error because the
value 3 is not compatible with the data type Array. If you disable strict mode, and run in
standard mode, the compiler does not complain about the type mismatch, but run-time type
checking by Flash Player results in a run-time error.
The following example shows a function named
but is passed a value of 3. This causes a run-time error in standard mode because the value 3 is
not a member of the parameter’s declared data type (Array).
function typeTest(xParam:Array)
{
trace(xParam);
}
var myNum:Number = 3;
typeTest(myNum);
// run-time error in ActionScript 3.0 standard mode
There may also be situations where you get a run-time type error even when you are operating
in strict mode. This is possible if you use strict mode, but opt out of compile-time type
checking by using an untyped variable. When you use an untyped variable, you are not
eliminating type checking, but rather deferring it until run time. For example, if the
variable in the previous example does not have a declared data type, the compiler cannot
detect the type mismatch, but Flash Player will generate a run-time error because it compares
the run-time value of
type of
xParam, which is set to the Array data type.
function typeTest(xParam:Array)
{
trace(xParam);
}
var myNum = 3;
typeTest(myNum);
// run-time error in ActionScript 3.0
myNum, which is set to 3 as a result of the assignment statement, with the
typeTest() that expects an Array argument
myNum
58ActionScript Language and Syntax
Page 59
Run-time type checking also allows more flexible use of inheritance than does compile-time
checking. By deferring type checking to run time, standard mode allows you to reference
properties of a subclass even if you upcast. An upcast occurs when you use a base class to
declare the type of a class instance, but a subclass to instantiate it. For example, you can create
a class named ClassBase that can be extended (classes with the
final attribute cannot be
extended):
class ClassBase
{
}
You can subsequently create a subclass of ClassBase named ClassExtender, which has one
property named
class ClassExtender extends ClassBase
{
var someString:String;
}
someString, as follows:
Using both classes, you can create a class instance that is declared using the ClassBase data
type, but instantiated using the ClassExtender constructor. Upcasts are considered safe
operations because the base class does not contain any properties or methods that are not in
the subclass.
var myClass:ClassBase = new ClassExtender();
A subclass, however, does contain properties or methods that its base class does not. For
example, the ClassExtender class contains the
someString property, which does not exist in
the ClassBase class. In ActionScript 3.0 standard mode, you can reference this property using
the
myClass instance without generating a compile-time error, as shown in the following
example:
var myClass:ClassBase = new ClassExtender();
myClass.someString = "hello";
// no error in ActionScript 3.0 standard mode
The is operator
The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or
expression is a member of a given data type. In previous versions of ActionScript, the
instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof
operator should not be used to test for data type membership. The
instead of the
instanceof y
instanceof operator for manual type checking because the expression x
merely checks the prototype chain of x for the existence of y (and in
ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance
hierarchy).
is operator should be used
Data types59
Page 60
The is operator examines the proper inheritance hierarchy and can be used to check not only
whether an object is an instance of a particular class, but also whether an object is an instance
of a class that implements a particular interface. The following example creates an instance of
the Sprite class named
mySprite and uses the is operator to test whether mySprite is an
instance of the Sprite and DisplayObject classes, and whether it implements the
IEventDispatcher interface:
var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject); // true
trace(mySprite is IEventDispatcher); // true
The is operator checks the inheritance hierarchy and properly reports that mySprite is
compatible with the Sprite and DisplayObject classes (the Sprite class is a subclass of the
DisplayObject class). The
is operator also checks whether mySprite inherits from any classes
that implement the IEventDispatcher interface. Because the Sprite class inherits from the
EventDispatcher class, which implements the IEventDispatcher interface, the
correctly reports that
mySprite implements the same interface.
The following example shows the same tests from the previous example, but with
instead of the
instance of Sprite or DisplayObject, but it returns
is operator. The instanceof operator correctly identifies that mySprite is an
The as operator, which is new in ActionScript 3.0, also allows you to check whether an
expression is a member of a given data type. Unlike the
does not return a Boolean value. Rather, the
instead of
the
true, and null instead of false. The following example shows the results of using
as operator instead of the is operator in the simple case of checking whether a Sprite
as operator returns the value of the expression
instance is a member of the DisplayObject, IEventDispatcher, and Number data types.
var mySprite:Sprite = new Sprite();
trace(mySprite as Sprite); // [object Sprite]
trace(mySprite as DisplayObject); // [object Sprite]
trace(mySprite as IEventDispatcher); // [object Sprite]
trace(mySprite as Number); // null
When you use the as operator, the operand on the right must be a data type. An attempt to
use an expression other than a data type as the operand on the right will result in an error.
60ActionScript Language and Syntax
is operator, however, the as operator
Page 61
Dynamic classes
A dynamic class defines an object that can be altered at run time by adding or changing
properties and methods. A class that is not dynamic, such as the String class, is a sealed class.
You cannot add properties or methods to a sealed class at run time.
You create dynamic classes by using the
example, the following code creates a dynamic class named
dynamic class Protean
{
private var privateGreeting:String = "hi";
public var publicGreeting:String = "hello";
function Protean()
{
trace("Protean instance created");
}
}
If you subsequently instantiate an instance of the Protean class, you can add properties or
methods to it outside the class definition. For example, the following code creates an instance
of the
Protean class and adds a property named aString and a property named aNumber to
the instance:
var myProtean:Protean = new Protean();
myProtean.aString = "testing";
myProtean.aNumber = 3;
trace(myProtean.aString, myProtean.aNumber); // testing 3
Properties that you add to an instance of a dynamic class are run-time entities, so any type
checking is done at run time. You cannot add a type annotation to a property that you add in
this manner.
You can also add a method to the
the function to a property of the
statement into a method named
var myProtean:Protean = new Protean();
myProtean.aString = "testing";
myProtean.aNumber = 3;
myProtean.traceProtean = function ()
{
myProtean instance by defining a function and attaching
myProtean instance. The following code moves the trace
traceProtean():
Data types61
Page 62
Methods created in this way, however, do not have access to any private properties or methods
of the Protean class. Moreover, even references to public properties or methods of the
Protean class must be qualified with either the this keyword or the class name. The
following example shows the
public variables of the
traceProtean() method attempting to access the private and
Protean class.
Data type descriptions
The primitive data types include Boolean, int, Null, Number, String, uint, and void. The
ActionScript core classes also define the following complex data types: Object, Array, Date,
Error, Function, RegExp, XML, and XMLList.
Boolean data type
The Boolean data type comprises two values: true and false. No other values are valid for
variables of Boolean type. The default value of a Boolean variable that has been declared but
not initialized is
false.
int data type
The int data type is stored internally as a 32-bit integer and comprises the set of integers from
-2,147,483,648 (-2
offered only the Number data type, which was used for both integers and floating point
numbers. In ActionScript 3.0, you now have access to low-level machine types for 32-bit
signed and unsigned integers. If your variable will not use floating point numbers, using the
int data type instead of the Number data type should be faster and more efficient.
For integer values outside the range of the minimum and maximum int values, use the
Number data type, which can handle values between positive and negative
9,007,199,254,740,992 (53-bit integer values). The default value for variables that are of the
data type int is 0.
62ActionScript Language and Syntax
31
) to 2,147,483,647 (231 - 1), inclusive. Previous versions of ActionScript
Page 63
Null data type
The Null data type contains only one value, null. This is the default value for the String data
type and all classes that define complex data types, including the Object class. None of the
other primitive data types, such as Boolean, Number, int and uint, contain the value
Flash Player will convert the value
assign
null to variables of type Boolean, Number, int, or uint. You cannot use this data type
null to the appropriate default value if you attempt to
null.
as a type annotation.
Number data type
In ActionScript 3.0, the Number data type can represent integers, unsigned integers, and
floating point numbers. However, to maximize performance, you should use the Number data
type only for integer values larger than the 32-bit
point numbers. To store a floating point number, include a decimal point in the number. If
you omit a decimal point, the number will be stored as an integer.
The Number data type uses the 64-bit double-precision format as specified by the IEEE
Standard for Binary Floating-Point Arithmetic (IEEE-754). This standard dictates how
floating point numbers are stored using the 64 available bits. One bit is used to designate
whether the number is positive or negative. Eleven bits are used for the exponent, which is
stored as base 2. The remaining 52 bits are used to store the significand (also called the
mantissa), which is the number that is raised to the power indicated by the exponent.
By using some of its bits to store an exponent, the Number data type can store floating point
numbers significantly larger than if it used all of its bits for the significand. For example, if the
Number data type used all 64 bits to store the significand, it could store a number as large as
64
2
. By using 11 bits to store an exponent, the Number data type can raise its significand to a
power of 2
1023
.
The maximum and minimum values that the Number type can represent are stored in static
properties of the Number class called
Although this range of numbers is enormous, the cost of this range is precision. The Number
data type uses 52 bits to store the significand, with the result that numbers that require more
than 52 bits to represent precisely, such as the fraction 1/3, are only approximations. If your
application requires absolute precision with decimal numbers, you need to use software that
implements decimal floating point arithmetic as opposed to binary floating point arithmetic.
int and uint types can store or for floating
Data types63
Page 64
When you store integer values with the Number data type, only the 52 bits of the significand
are used. The Number data type uses these 52 bits and a special hidden bit to represent
integers from -9,007,199,254,740,992 (-2
Flash Player uses the
NaN value not only as the default value for variables of type Number, but
53
) to 9,007,199,254,740,992 (253).
also as the result of any operation that should return a number but does not. For example, if
you attempt to calculate the square root of a negative number, the result will be
special Number values include positive infinity and negative infinity
.
NOTE
The result of division by 0 is only NaN if the divisor is also 0. Division by 0 produces
infinity when the dividend is positive or -infinity when the dividend is negative.
.
NaN. Other
String data type
The String data type represents a sequence of 16-bit characters. Strings are stored internally as
Unicode characters, using the UTF-16 format. Strings are immutable values, just as they are
in the Java programming language. An operation on a String value returns a new instance of
the string. The default value for a variable declared with the String data type is
value
null is not the same as the empty string (""), even though they both represent the
null. The
absence of any characters.
uint data type
The uint data type is stored internally as a 32-bit unsigned integer and comprises the set of
integers from 0 to 4,294,967,295 (2
circumstances that call for non-negative integers. For example, you must use the uint data
type to represent pixel color values because the int data type has an internal sign bit that is not
appropriate for handling color values. For integer values larger than the maximum uint value,
use the Number data type, which can handle 53-bit integer values. The default value for
variables that are of data type uint is 0.
32
-1), inclusive. Use the uint data type for special
void data type
The void data type contains only one value, undefined. In previous versions of ActionScript,
undefined was the default value for instances of the Object class. In ActionScript 3.0, the
default value for Object instances is
instance of the Object class, Flash Player will convert the value to
value of
undefined to variables that are untyped. Untyped variables are variables that either
lack any type annotation, or use the asterisk (
only as a return type annotation.
64ActionScript Language and Syntax
null. If you attempt to assign the value undefined to an
null. You can only assign a
*) symbol for type annotation. You can use void
Page 65
Object data type
The Object data type is defined by the Object class. The Object class serves as the base class
for all class definitions in ActionScript. The ActionScript 3.0 version of the Object data type
differs from that of previous versions in three ways. First, the Object data type is no longer the
default data type assigned to variables with no type annotation. Second, the Object data type
no longer includes the value
instances. Third, in ActionScript 3.0, the default value for instances of the Object class is
null.
In previous versions of ActionScript, a variable with no type annotation was automatically
assigned the Object data type. This is no longer true in ActionScript 3.0, which now includes
the idea of a truly untyped variable. Variables with no type annotation are now considered
untyped. If you prefer to make it clear to readers of your code that your intention is to leave a
variable untyped, you can use the new asterisk (
equivalent to omitting a type annotation. The following example shows two equivalent
statements, both of which declare an untyped variable
var x
var x:*
Only untyped variables can hold the value undefined. If you attempt to assign the value
undefined to a variable that has a data type, Flash Player will convert the value undefined to
the default value of that data type. For instances of the Object data type, the default value is
null, which means that Flash Player will convert the value undefined to null if you attempt
to assign
undefined to an Object instance.
undefined, which used to be the default value of Object
*) symbol for the type annotation, which is
x:
Type conversions
A type conversion is said to occur when a value is transformed into a value of a different data
type. Type conversions can be either implicit or explicit. Implicit conversion, which is also
called coercion, is sometimes performed by Flash Player at run time. For example, if the value
2 is assigned to a variable of the Boolean data type, Flash Player converts the value 2 to the
Boolean value
also called casting, occurs when your code instructs the compiler to treat a variable of one data
type as if it belongs to a different data type. When primitive values are involved, casting
actually converts values from one data type to another. To cast an object to a different type,
you wrap the object name in parentheses and precede it with the name of the new type. For
example, the following code takes a Boolean value and casts it to an integer:
var myBoolean:Boolean = true;
var myINT:int = int(myBoolean);
trace(myINT); // 1
true before assigning the value to the variable. Explicit conversion, which is
Data types65
Page 66
Implicit conversions
Implicit conversions happen at run time in a number of contexts:
■ In assignment statements
■ When values are passed as function arguments
■ When values are returned from functions
■ In expressions using certain operators, such as the addition (+) operator
For user-defined types, implicit conversions succeed when the value to be converted is an
instance of the destination class or a class that derives from the destination class. If an implicit
conversion is unsuccessful, an error occurs. For example, the following code contains a
successful implicit conversion and an unsuccessful implicit conversion:
class A {}
class B extends A {}
var objA:A = new A();
var objB:B = new B();
var arr:Array = new Array();
For primitive types, implicit conversions are handled by calling the same internal conversion
algorithms that are called by the explicit conversion functions. The following sections discuss
these primitive type conversions in detail.
Explicit conversions
It’s helpful to use explicit conversions, or casting, when you compile in strict mode because
there may be times when you do not want a type mismatch to generate a compile-time error.
This may be the case when you know that coercion will convert your values correctly at run
time. For example, when working with data received from a form, you may want to rely on
coercion to convert certain string values to numeric values. The following code generates a
compile-time error even though the code would run correctly in standard mode.
var quantityField:String = "3";
var quantity:int = quantityField; // compile time error in strict mode
If you want to continue using strict mode, but would like the string converted to an integer,
you can use explicit conversion, as follows:
var quantityField:String = "3";
var quantity:int = int(quantityField); // Explicit conversion succeeds.
66ActionScript Language and Syntax
Page 67
Casting to int, uint, and Number
You can cast any data type into one of the three number types: int, uint, and Number. If Flash
Player is unable to convert the number for some reason, the default value of 0 is assigned for
the int and uint data types, and the default value of
If you convert a Boolean value to a number,
value 0.
String values that contain only digits can be successfully converted into one of the number
types. The number types can also convert strings that look like negative numbers or strings
that represent a hexadecimal value (for example,
leading and trailing white space characters in the string value. You can also cast strings that
look like floating point numbers using
uint() and int() to return an integer with the characters following the decimal that has
Number(). The inclusion of a decimal point causes
been truncated. For example, the following string values can be cast into numbers.
trace(uint("5")); // 5
trace(uint("-5")); // 4294967291. It wraps around from MAX_VALUE
trace(uint(" 27 ")); // 27
trace(uint("3.7")); // 3
trace(int("3.7")); // 3
trace(int("0x1A")); // 26
trace(Number("3.7")); // 3.7
String values that contain non-numeric characters return 0 when cast with int() or uint()
and
NaN when case with Number(). The conversion process ignores leading and trailing white
NaN if a string has white space separating two numbers.
NaN is assigned for the Number data type.
true becomes the value 1 and false becomes the
0x1A). The conversion process ignores
Data types67
Page 68
In ActionScript 3.0, the Number() function no longer supports octal, or base 8, numbers. If
you supply a string with a leading zero to the ActionScript 2.0
Number() function, the
number is interpreted as an octal number, and converted to its decimal equivalent. This is not
true with the
Number() function in ActionScript 3.0, which instead ignores the leading zero.
For example, the following code generates different output when compiled using different
versions of ActionScript:
Casting is not necessary when a value of one numeric type is assigned to a variable of a
different numeric type. Even in strict mode, the numeric types are implicitly converted to the
other numeric types. This means that in some cases, unexpected values may result when the
range of a type is exceeded. The following examples all compile in strict mode, though some
will generate unexpected values:
var sampleUINT:uint = -3; // Assign value of type int and Number.
trace(sampleUINT); // 4294967293
var sampleNum:Number = sampleUINT; // Assign value of type int and uint.
trace(sampleNum) // 4294967293
var sampleINT:int = uint.MAX_VALUE + 1; // Assign value of type Number.
trace(sampleINT); // 0
sampleINT = int.MAX_VALUE + 1; // Assign value of type uint and Number.
trace(sampleINT); // -2147483648
The following table summarizes the results of casting to the Number, int, or uint data type
from other data types.
Data type or value Result of conversion to Number, int or uint
BooleanIf the value is true, 1; otherwise, 0.
DateThe internal representation of the Date object, which is the number
of milliseconds since midnight January 1, 1970, universal time.
null
ObjectIf the instance is
StringA number if Flash Player can convert the string to a number;
undefined
68ActionScript Language and Syntax
0
null and converted to Number, NaN; otherwise, 0.
otherwise,
If converted to Number, NaN; if converted to int or uint, 0.
NaN if converted to Number or 0 if converted to int or uint.
Page 69
Casting to Boolean
Casting to Boolean from any of the numeric data types (uint, int, and Number) results in
false if the numeric value is 0, and true otherwise. For the Number data type, the value NaN
also results in
and 1:
var myNum:Number;
for (myNum = -1; myNum<2; myNum++)
{
trace("Boolean(" + myNum +") is " + Boolean(myNum));
}
The output from the example shows that of the three numbers, only 0 returns a value of
false:
Boolean(-1) is true
Boolean(0) is false
Boolean(1) is true
Casting to Boolean from a String value returns false if the string is either null or an empty
string (
var str1:String; // Uninitialized string is null.
trace(Boolean(str1)); // false
var str2:String = ""; // empty string
trace(Boolean(str2)); // false
var str3:String = " "; // white space only
trace(Boolean(str3)); // true
Casting to Boolean from an instance of the Object class returns false if the instance is null,
and
true otherwise, as the following example shows:
var myObj:Object; // Uninitialized object is null.
trace(Boolean(myObj)); // false
false. The following example shows the results of casting the numbers -1, 0,
""). Otherwise, it returns true.
myObj = new Object(); // instantiate
trace(Boolean(myObj)); // true
Data types69
Page 70
Boolean variables get special treatment in strict mode in that you can assign values of any data
type to a Boolean variable without casting. Implicit coercion from all data types to the
Boolean data type occurs even in strict mode. In other words, unlike almost all other data
types, casting to Boolean is not necessary to avoid strict mode errors. The following examples
all compile in strict mode and behave as expected at run time:
var myObj:Object = new Object(); // instantiate
var bool:Boolean = myObj;
trace(bool); // true
bool = "random string";
trace(bool); // true
bool = new Array();
trace(bool); // true
bool = NaN;
trace(bool); // false
The following table summarizes the results of casting to the Boolean data type from other data
types:
Data type or value Result of conversion to Boolean
Stringfalse if the value is null or the empty string (""); true otherwise.
nullfalse
Number, int or uintfalse if the value is NaN or 0; true otherwise.
Objectfalse if the instance is null; true otherwise.
Casting to String
Casting to the String data type from any of the numeric data types returns a string
representation of the number. Casting to the String data type from a Boolean value returns the
string
“true” if the value is true, and returns the string “false” if the value is false.
Casting to the String data type from an instance of the Object class returns the string
if the instance is
string
“[object Object]”.
null. Otherwise, casting to the String type from the Object class returns the
Casting to String from an instance of the Array class returns a string comprising a commadelimited list of all the array elements. For example, the following cast to the String data type
returns one string containing all three elements of the array:
var myArray:Array = ["primary", "secondary", "tertiary"];
trace(String(myArray)); // primary,secondary,tertiary
“null”
70ActionScript Language and Syntax
Page 71
Casting to String from an instance of the Date class returns a string representation of the date
that the instance contains. For example, the following example returns a string representation
of the Date class instance (the output shows result for Pacific Daylight Time):
var myDate:Date = new Date(2005,6,1);
trace(String(myDate)); // Fri Jul 1 00:00:00 GMT-0700 2005
The following table summarizes the results of casting to the String data type from other data
types.
Data type or value Result of conversion to string
ArrayA string comprising all array elements.
Boolean"true" or "false"
DateA string representation of the Date object.
null"null"
Number, int or uintA string representation of the number.
ObjectIf the instance is null,
"null"; otherwise, "[object Object]”.
Syntax
The syntax of a language defines a set of rules that must be followed when writing executable
code.
Case sensitivity
ActionScript 3.0 is a case-sensitive language. Identifiers that differ only in case are considered
different identifiers. For example, the following code creates two different variables:
var num1:int;
var Num1:int;
Dot syntax
The dot operator (.) provides a way to access the properties and methods of an object. Using
dot syntax, you can refer to a class property or method using an instance name, followed by
the dot operator and name of the property or method. For example, consider the following
class definition:
class DotExample
{
public var prop1:String;
Syntax71
Page 72
public function method1():void {}
}
Using dot syntax, you can access the prop1 property and the method1() method using the
instance name created in the following code:
var myDotEx:DotExample = new DotExample();
myDotEx.prop1 = “hello”;
myDotEx.method1();
You can use dot syntax when you define packages. You use the dot operator to refer to nested
packages. For example, the EventDispatcher class resides in a package named events that is
nested within the package named flash. You can refer to the events package using the
following expression:
flash.events
You can also refer to the EventDispatcher class using this expression:
flash.events.EventDispatcher
Slash syntax
Slash syntax is not supported in ActionScript 3.0. Slash syntax was used in earlier versions of
ActionScript to indicate the path of a movie clip or variable.
Literals
A literal is a value that appears directly in your code. The following examples are all literals:
17
"hello"
-3
9.4
null
undefined
true
false
Literals can also be grouped to form compound literals. Array literals are enclosed in bracket
characters (
[]) and use the comma to separate array elements.
72ActionScript Language and Syntax
Page 73
An array literal can be used to initialize an array. The following examples show two arrays that
are initialized using array literals. You can use the
new statement and pass the compound
literal as a parameter to the Array class constructor, but you can also assign literal values
directly when instantiating instances of the following ActionScript core classes: Object, Array,
String, Number, int, uint, XML, XMLList and Boolean.
// Use new statement.
var myStrings:Array = new Array(["alpha", "beta", "gamma"]);
var myNums:Array = new Array([1,2,3,5,8]);
// Assign literal directly.
var myStrings:Array = ["alpha", "beta", "gamma"];
var myNums:Array = [1,2,3,5,8];
Literals can also be used to initialize a generic object. A generic object is an instance of the
Object class. Object literals are enclosed in curly braces (
object properties. Each property is declared with the colon character (
{}) and use the comma to separate
:), which separates the
name of the property from the value of the property.
You can create a generic object using the
new statement, and pass the object literal as a
parameter to the Object class constructor, or you can assign the object literal directly to the
instance you are declaring. The following example creates a new generic object and initializes
the object with three properties (
propA, propB, and propC), each with values set to 1, 2, and
3, respectively.
// Use new statement.
var myObject:Object = new Object({propA:1, propB:2, propC:3});
// Assign literal directly.
var myObject:Object = {propA:1, propB:2, propC:3};
For more information, see “Creating strings” on page 209, “Introduction to Regular
Expressions” on page 286, and “Initializing XML variables” on page 319.
Semicolons
You can use the semicolon character (;) to terminate a statement. Alternatively, if you omit
the semicolon character, the compiler will assume that each line of code represents a single
statement. Because many programmers are accustomed to using the semicolon to denote the
end of a statement, your code may be easier to read if you consistently use semicolons to
terminate your statements.
Using a semicolon to terminate a statement allows you to place more than one statement on a
single line, but this may make your code more difficult to read.
Syntax73
Page 74
Parentheses
You can use parentheses (()) in three ways in ActionScript 3.0. First, you can use parentheses
to change the order of operations in an expression. Operations that are grouped inside
parentheses are always executed first. For example, parentheses are used to alter the order of
operations in the following code:
Second, you can use parentheses with the comma operator (,) to evaluate a series of
expressions and return the result of the final expression, as shown in the following example:
var a:int = 2;
var b:int = 3;
trace((a++, b++, a+b)); // 7
Third, you can use parentheses to pass one or more parameters to functions or methods, as
shown in the following example, which passes a String value to the
trace("hello"); // hello
trace() function:
Comments
ActionScript 3.0 code supports two types of comments: single-line comments and multiline
comments. These commenting mechanisms are similar to the commenting mechanisms in
C++ and Java. The compiler will ignore text that is marked as a comment.
Single-line comments begin with two forward slash characters (
of the line. For example, the following code contains a single-line comment:
var someNumber:Number = 3; // a single line comment
Multiline comments begin with a forward slash and asterisk (/*) and end with an asterisk and
forward slash (
/* This is multiline comment that can span
more than one line of code. */
*/).
//) and continue until the end
74ActionScript Language and Syntax
Page 75
Keywords and reserved words
Reserved words are words that you cannot use as identifiers in your code because the words are
reserved for use by ActionScript. Reserved words include lexical keywords, which are removed
from the program namespace by the compiler. The compiler will report an error if you use a
lexical keyword as an identifier. The following table lists ActionScript 3.0 lexical keywords.
asbreakcasecatch
classconstcontinuedefault
deletedoelseextends
falsefinallyforfunction
ifimplementsimportin
instanceofinterfaceinternalis
nativenewnullpackage
privateprotectedpublicreturn
superswitchthisthrow
totruetrytypeof
usevarvoidwhile
with
There is a small set of keywords, called syntactic keywords, that can be used as identifiers, but
that have special meaning in certain contexts. The following table lists ActionScript 3.0
syntactic keywords.
eachgetsetnamespace
includedynamicfinalnative
overridestatic
Syntax75
Page 76
There are also several identifiers that are sometimes referred to as future reserved words. These
identifiers are not reserved by ActionScript 3.0, though some of them may be treated as
keywords by products that incorporate ActionScript 3.0. You might be able to use many of
these identifiers in your code, but Adobe recommends that you do not use them because they
may appear as keywords in a subsequent version of the language.
abstractbooleanbytecast
chardebuggerdoubleenum
exportfloatgotointrinsic
longprototypeshortsynchronized
throwstotransienttype
virtualvolatile
Constants
ActionScript 3.0 supports the const statement, which you can use to create constants.
Constants are properties with a fixed value that cannot be altered. You can assign a value to a
constant only once, and the assignment must occur in close proximity to the declaration of
the constant. For example, if a constant is declared as a member of a class, you can assign a
value to that constant only as part of the declaration or inside the class constructor.
The following code declares two constants. The first constant, MINIMUM, has a value
assigned as part of the declaration statement. The second constant, MAXIMUM, has a value
assigned in the constructor.
class A
{
public const MINIMUM:int = 0;
public const MAXIMUM:int;
public function A()
{
MAXIMUM = 10;
}
}
var a:A = new A();
trace(a.MINIMUM); // 0
trace(a.MAXIMUM); // 10
76ActionScript Language and Syntax
Page 77
An error results if you attempt to assign an initial value to a constant in any other way. For
example, if you attempt to set the initial value of
MAXIMUM outside the class, a run-time error
will occur.
class A
{
public const MINIMUM:int = 0;
public const MAXIMUM:int;
}
var a:A = new A();
a["MAXIMUM"] = 10; // run-time error
The Flash Player API defines a wide range of constants for your use. By convention, constants
in ActionScript use all capital letters, with words separated by the underscore character (
_ ).
For example, the MouseEvent class definition uses this naming convention for its constants,
each of which represents an event related to mouse input:
package flash.events
{
public class MouseEvent extends Event
{
public static const CLICK:String = "click";
public static const DOUBLE_CLICK:String = "doubleClick";
public static const MOUSE_DOWN:String = "mouseDown";
public static const MOUSE_MOVE:String = "mouseMove";
...
}
}
Operators
Operators are special functions that take one or more operands and return a value. An operand
is a value—usually a literal, a variable, or an expression—that an operator uses as input. For
example, in the following code, the addition (
with three literal operands (2, 3
assignment (
var sumNumber:uint = 2 + 3 * 4; // uint = 14
=) operator to assign the returned value, 14, to the variable sumNumber.
, and 4) to return a value. This value is then used by the
Operators can be unary, binary, or ternary. A unary operator takes one operand. For example,
the increment (
++) operator is a unary operator because it takes only one operand. A binary
operator takes two operands. For example, the division (
ternary operator takes three operands. For example, the conditional (
operands.
+) and multiplication (*) operators are used
/) operator takes two operands. A
?:) operator takes three
Operators77
Page 78
Some operators are overloaded, which means that they behave differently depending on the
type or quantity of operands passed to them. The addition (
+) operator is an example of an
overloaded operator that behaves differently depending on the data type of the operands. If
both operands are numbers, the addition operator returns the sum of the values. If both
operands are strings, the addition operator returns the concatenation of the two operands.
The following example code shows how the operator behaves differently depending on the
operands.
trace(5 + 5); // 10
trace("5" + "5"); // 55
Operators can also behave differently based on the number of operands supplied. The
subtraction (
-) operator is both a unary and binary operator. When supplied with only one
operand, the subtraction operator negates the operand and returns the result. When supplied
with two operands, the subtraction operator returns the difference between the operands. The
following example shows the subtraction operator used first as a unary operator, and then as a
binary operator.
trace(-3); // -3
trace(7-2); // 5
Operator precedence and associativity
Operator precedence and associativity determine the order in which operators are processed.
Although it may seem natural to those familiar with arithmetic that the compiler processes the
multiplication (
instructions about which operators to process first. Such instructions are collectively referred
to as operator precedence. ActionScript defines a default operator precedence that you can alter
using the parentheses (
precedence in the previous example to force the compiler to process the addition operator
before the multiplication operator:
var sumNumber:uint = (2 + 3) * 4; // uint == 20
You may encounter situations in which two or more operators of the same precedence appear
in the same expression. In these cases, the compiler uses the rules of associativity to determine
which operator to process first. All of the binary operators, except the assignment operators,
are left-associative, which means that operators on the left are processed before operators on
the right. The assignment operators and the conditional (
which means that the operators on the right are processed before operators on the left.
*) operator before the addition (+) operator, the compiler needs explicit
()) operator. For example, the following code alters the default
?:) operator are right-associative,
78ActionScript Language and Syntax
Page 79
For example, consider the less-than (<) and greater-than (>) operators, which have the same
precedence. If both operators are used in the same expression, the operator on the left is
processed first because both operators are left-associative. This means that the following two
statements produce the same output:
The greater-than operator is processed first, which results in a value of true because the
operand 3 is greater than the operand 2. The value
true is then passed to the less-than
operator, along with the operand 1. The following code represents this intermediate state:
trace((true) < 1);
The less-than operator converts the value true to the numeric value 1 and compares that
numeric value to the second operand 1 to return the value
false (the value 1 is not less than
1).
trace(1 < 1); // false
You can alter the default left associativity with the parentheses (()) operator. You can instruct
the compiler to process the less-than operator first by enclosing that operator and its operands
in parentheses. The following example uses the parentheses operator to produce a different
output using the same numbers as the previous example:
trace(3 > (2 < 1)); // true
The less-than operator is processed first, which results in a value of false because the operand
2 is not less than the operand 1. The value
false is then passed to the greater-than operator,
along with the operand 3. The following code represents this intermediate state:
trace(3 > (false));
The greater-than operator converts the value false to the numeric value 0 and compares that
numeric value to the other operand 3 to return
trace(3 > 0); // true
true (the value 3 is greater than 0).
The following table lists the operators for ActionScript 3.0 in order of decreasing precedence.
Each row of the table contains operators of the same precedence. Each row of operators has
higher precedence than the row appearing below it in the table.
GroupOperators
Primary
Postfix
Unary
Multiplicative
[] {x:y} () f(x) new x.y x[y] <></> @ :: ..
x++ x--
++x --x + - ~ ! delete typeof void
* / %
Operators79
Page 80
GroupOperators
Additive
Bitwise shift
Relational
Equality
Bitwise AND
Bitwise XOR
Bitwise OR
Logical AND
Logical OR
Conditional
Assignment
Comma
+ -
<< >> >>>
< > <= >= as in instanceof is
== != === !==
&
^
|
&&
||
?:
= *= /= %= += -= <<= >>= >>>= &= ^= |=
,
Primary operators
The primary operators include those used for creating Array and Object literals, grouping
expressions, calling functions, instantiating class instances, and accessing properties.
All the primary operators, as listed in the following table, have equal precedence. Operators
that are part of the E4X specification are indicated by the (E4X) notation.
OperatorOperation performed
[]
{x:y}
()
f(x)
new
x.y x[y]
<></>
@
::
..
Initializes an array
Initializes an object
Groups expressions
Calls a function
Calls a constructor
Accesses a property
Initializes an XMLList object (E4X)
Accesses an attribute (E4X)
Qualifies a name (E4X)
Accesses a descendant XML element (E4X)
80ActionScript Language and Syntax
Page 81
Postfix operators
The postfix operators take one operator and either increment or decrement the value.
Although these operators are unary operators, they are classified separately from the rest of the
unary operators because of their higher precedence and special behavior. When a postfix
operator is used as part of a larger expression, the expression’s value is returned before the
postfix operator is processed. For example, the following code shows how the value of the
expression
var xNum:Number = 0;
trace(xNum++); // 0
trace(xNum); // 1
xNum++ is returned before the value is incremented:
All the postfix operators, as listed in the following table, have equal precedence:
OperatorOperation performed
++
--
Increments (postfix)
Decrements (postfix)
Unary operators
The unary operators take one operand. The increment (++) and decrement (--) operators in
this group are prefix operators, which means that they appear before the operand in an
expression. The prefix operators differ from their postfix counterparts in that the increment or
decrement operation is completed before the value of the overall expression is returned. For
example, the following code shows how the value of the expression
the value is incremented:
var xNum:Number = 0;
trace(++xNum); // 1
trace(xNum); // 1
All the unary operators, as listed in the following table, have equal precedence:
++xNum is returned after
OperatorOperation performed
++
--
+
-
!
~
Increments (prefix)
Decrements (prefix)
Unary +
Unary - (negation)
Logical NOT
Bitwise NOT
Operators81
Page 82
OperatorOperation performed
delete
typeof
void
Deletes a property
Returns type information
Returns undefined value
Multiplicative operators
The multiplicative operators take two operands and perform multiplication, division, or
modulo calculations.
All the multiplicative operators, as listed in the following table, have equal precedence:
OperatorOperation performed
*
/
%
Multiplication
Division
Modulo
Additive operators
The additive operators take two operands and perform addition or subtraction calculations.
All the additive operators, as listed in the following table, have equal precedence:
OperatorOperation performed
+
-
Addition
Subtraction
Bitwise shift operators
The bitwise shift operators take two operands and shift the bits of the first operand to the
extent specified by the second operand. All the bitwise shift operators, as listed in the
following table, have equal precedence:
OperatorOperation performed
<<
>>
>>>
82ActionScript Language and Syntax
Bitwise left shift
Bitwise right shift
Bitwise unsigned right shift
Page 83
Relational operators
The relational operators take two operands, compare their values, and return a Boolean value.
All the relational operators, as listed in the following table, have equal precedence:
OperatorOperation performed
<
>
<=
>=
as
in
instanceof
is
Less than
Greater than
Less than or equal to
Greater than or equal to
Checks data type
Checks for object properties
Checks prototype chain
Checks data type
Equality operators
The equality operators take two operands, compare their values, and return a Boolean value.
All the equality operators, as listed in the following table, have equal precedence:
OperatorOperation performed
==
!=
===
!==
Equality
Inequality
Strict equality
Strict inequality
Bitwise logical operators
The bitwise logical operators take two operands and perform bit-level logical operations. The
bitwise logical operators differ in precedence and are listed in the following table in order of
decreasing precedence:
OperatorOperation performed
&
^
|
Bitwise AND
Bitwise XOR
Bitwise OR
Operators83
Page 84
Logical operators
The logical operators take two operands and return a Boolean result. The logical operators
differ in precedence and are listed in the following table in order of decreasing precedence:
OperatorOperation performed
&&
||
Logical AND
Logical OR
Conditional operator
The conditional operator is a ternary operator, which means that it takes three operands. The
conditional operator is a shorthand method of applying the
OperatorOperation performed
?:
Conditional
if..else conditional statement.
Assignment operators
The assignment operators take two operands and assign a value to one operand based on the
value of the other operand. All the assignment operators, as listed in the following table, have
equal precedence:
OperatorOperation performed
=
*=
/=
%=
+=
-=
<<=
>>=
>>>=
&=
^=
|=
Assignment
Multiplication assignment
Division assignment
Modulo assignment
Addition assignment
Subtraction assignment
Bitwise left shift assignment
Bitwise right shift assignment
Bitwise unsigned right shift assignment
Bitwise AND assignment
Bitwise XOR assignment
Bitwise OR assignment
84ActionScript Language and Syntax
Page 85
Conditionals
ActionScript 3.0 provides three basic conditional statements that you can use to control
program flow.
if..else
The if..else conditional statement allows you to test a condition and execute a block of
code if that condition exists, or execute an alternative block of code if the condition does not
exist. For example, the following code tests whether the value of
trace() function if it does, or generates a different trace() function if it does not:
if (x > 20)
{
trace("x is > 20");
}
else
{
trace("x is <= 20");
}
If you do not want to execute an alternative block of code, you can use the if statement
without the
else statement.
x exceeds 20, generates a
Conditionals85
Page 86
if..else if
You can test for more than one condition using the if..else if conditional statement. For
example, the following code not only tests whether the value of
whether the value of
if (x > 20)
{
trace("x is > 20");
}
else if (x < 0)
{
trace("x is negative");
}
x is negative:
If an if or else statement is followed by only one statement, the statement does not need to
be enclosed in braces. For example, the following code does not use braces.
if (x > 0)
trace("x is positive”);
else if (x < 0)
trace("x is negative");
else
trace("x is 0");
However, Adobe recommends that you always use braces because unexpected behavior can
occur if statements are later added to a conditional statement that lacks braces. For example,
in the following code the value of
evaluates to
var x:int;
var positiveNums:int = 0;
true:
positiveNums increases by 1 whether or not the condition
x exceeds 20, but also tests
if (x > 0)
trace("x is positive");
positiveNums++;
trace(positiveNums); // 1
86ActionScript Language and Syntax
Page 87
switch
The switch statement is useful if you have several execution paths that depend on the same
condition expression. It provides functionality similar to a long series of
statements, but is somewhat easier to read. Instead of testing a condition for a Boolean value,
the
switch statement evaluates an expression and uses the result to determine which block of
code to execute. Blocks of code begin with a
For example, the following
number returned by the
var someDate:Date = new Date();
var dayNum:uint = someDate.getDay();
switch(dayNum)
{
case 0:
trace("Sunday");
break;
case 1:
trace("Monday");
break;
case 2:
trace("Tuesday");
break;
case 3:
trace("Wednesday");
break;
case 4:
trace("Thursday");
break;
case 5:
trace("Friday");
break;
case 6:
trace("Saturday");
break;
default:
trace("Out of range");
break;
}
switch statement prints the day of the week based on the day
Date.getDay() method:
case statement, and end with a break statement.
if..else if
Conditionals87
Page 88
Looping
Looping statements allow you to perform a specific block of code repeatedly using a series of
values or variables. Adobe recommends that you always enclose the block of code in braces
(
{}). Although you can omit the braces if the block of code contains only one statement, this
practice is not recommended for the same reason that it is not recommended for conditionals:
it increases the likelihood that statements added later will be inadvertently excluded from the
block of code. If you later add a statement that you want to include in the block of code, but
forget to add the necessary braces, the statement will not be executed as part of the loop.
for
The for loop allows you to iterate through a variable for a specific range of values. You must
supply three expressions in a
conditional statement that determines when the looping ends, and an expression that changes
the value of the variable with each loop. For example, the following code loops five times. The
value of the variable
i starts at 0 and ends at 4, and the output will be the numbers 0 through
4, each on its own line.
var i:int;
for (i = 0; i < 5; i++)
{
trace(i);
}
for statement: a variable that is set to an initial value, a
for..in
The for..in loop iterates through the properties of an object, or the elements of an array. For
example, you can use a
(object properties are not kept in any particular order, so properties may appear in a seemingly
random order):
var myObj:Object = {x:20, y:30};
for (var i:String in myObj)
{
You can also iterate through the elements of an array:
var myArray:Array = ["one", "two", "three"];
for (var i:String in myArray)
88ActionScript Language and Syntax
for..in loop to iterate through the properties of a generic object
Page 89
{
trace(myArray[i]);
}
// output:
// one
// two
// three
What you cannot do is iterate through the properties of an object if it is an instance of a userdefined class, unless the class is a dynamic class. Even with instances of dynamic classes, you
will be able to iterate only through properties that are added dynamically.
for each..in
The for each..in loop iterates through the items of a collection, which can be tags in an
XML or XMLList object, the values held by object properties, or the elements of an array. For
example, as the following excerpt shows, you can use a
the properties of a generic object, but unlike the
each..in
var myObj:Object = {x:20, y:30};
for each (var num in myObj)
{
}
// output:
// 20
// 30
loop contains the value held by the property instead of the name of the property:
trace(num);
You can iterate through an XML or XMLList object, as the following example shows:
var myXML:XML = <users>
<fname>Jane</fname>
<fname>Susan</fname>
<fname>John</fname>
</users>;
for each..in loop to iterate through
for..in loop, the iterator variable in a for
for each (var item in myXML.fname)
{
trace(item);
}
/* output
Jane
Susan
John
*/
Looping89
Page 90
You can also iterate through the elements of an array, as this example shows:
var myArray:Array = ["one", "two", "three"];
for each (var item in myArray)
{
trace(item);
}
// output:
// one
// two
// three
You cannot iterate through the properties of an object if the object is an instance of a sealed
class. Even for instances of dynamic classes, you cannot iterate through any fixed properties,
which are properties defined as part of the class definition.
while
The while loop is like an if statement that repeats as long as the condition is true. For
example, the following code produces the same output as the
var i:int = 0;
while (i < 5)
{
trace(i);
i++;
}
One disadvantage of using a while loop instead of a for loop is that infinite loops are easier
to write with
while loops. The for loop example code does not compile if you omit the
expression that increments the counter variable, but the
you omit that step. Without the expression that increments
loop.
for loop example:
while loop example does compile if
i, the loop becomes an infinite
do..while
The do..while loop is a while loop that guarantees that the code block is executed at least
once, because the condition is checked after the code block is executed. The following code
shows a simple example of a
is not met:
var i:int = 5;
do
{
trace(i);
i++;
90ActionScript Language and Syntax
do..while loop that generates output even though the condition
Page 91
} while (i < 5);
// output: 5
Functions
Functions are blocks of code that carry out specific tasks and can be reused in your program.
There are two types of functions in ActionScript 3.0: methods and function closures. Whether a
function is a called a method or a function closure depends on the context in which the
function is defined. A function is called a method if you define it as part of a class definition
or attach it to an instance of an object. A function is called a function closure if it is defined in
any other way.
Functions have always been extremely important in ActionScript. In ActionScript 1.0, for
example, the
Although the
functions is still important if you want to take full advantage of what the language has to offer.
This can be a challenge for programmers who expect ActionScript functions to behave
similarly to functions in languages such as C++ or Java. Although basic function definition
and invocation should not present a challenge to experienced programmers, some of the more
advanced features of ActionScript functions require some explanation.
Basic function concepts
This section discusses basic function definition and invocation techniques.
class keyword did not exist, so “classes” were defined by constructor functions.
class keyword has since been added to the language, a solid understanding of
Calling functions
You call a function by using its identifier followed by the parentheses operator (()). You use
the parentheses operator to enclose any function parameters you want to send to the function.
For example, the
used throughout this book:
trace(“Use trace to help debug your script”);
If you are calling a function with no parameters, you must use an empty pair of parentheses.
For example, you can use the
generate a random number:
var randomNum:Number = Math.random();
trace() function, which is a top-level function in the Flash Player API, is
Math.random() method, which takes no parameters, to
Functions91
Page 92
Defining your own functions
There are two ways to define a function in ActionScript 3.0: you can use a function statement
or a function expression. The technique you choose depends on whether you prefer a more
static or dynamic programming style. Define your functions with function statements if you
prefer static, or strict mode, programming. Define your functions with function expressions if
you have a specific need to do so. Function expressions are more often used in dynamic, or
standard mode, programming.
Function statements
Function statements are the preferred technique for defining functions in strict mode. A
function statement begins with the
■ The function name.
■ The parameters, in a comma-delimited list enclosed in parentheses.
■ The function body—that is, the ActionScript code to be executed when the function is
invoked, enclosed in curly braces.
For example, the following code creates a function that defines a parameter and then invokes
the function using the string “
function traceParameter(aParam:String)
{
trace(aParam);
}
function keyword, followed by:
hello” as the parameter value:
traceParameter("hello"); // hello
Function expressions
The second way to declare a function is to use an assignment statement with a function
expression, which is also sometimes called a function literal or an anonymous function. This
is a more verbose method that is widely used in earlier versions of ActionScript.
92ActionScript Language and Syntax
Page 93
An assignment statement with a function expression begins with the var keyword, followed by:
■ The function name
■ The colon operator (:)
■ The Function class to indicate the data type
■ The assignment operator (=)
■ The function keyword
■ The parameters, in a comma-delimited list enclosed in parentheses
■ The function body—that is, the ActionScript code to be executed when the function is
invoked, enclosed in curly braces
For example, the following code declares the
traceParameter function using a function
expression:
var traceParameter:Function = function (aParam:String)
{
Notice that you do not specify a function name, as you do in a function statement. Another
important difference between function expressions and function statements is that a function
expression is an expression rather than a statement. This means that a function expression
cannot stand on its own, as a function statement can. A function expression can be used only
as a part of a statement, usually an assignment statement. The following example shows a
function expression assigned to an array element:
var traceArray:Array = new Array();
traceArray[0] = function (aParam:String)
{
trace(aParam);
};
traceArray[0]("hello");
Choosing between statements and expressions
As a general rule, use a function statement unless specific circumstances call for the use of an
expression. Function statements are less verbose, and they provide a more consistent
experience between strict mode and standard mode than function expressions.
Function statements are easier to read than assignment statements that contain function
expressions. Function statements make your code more concise; they are less confusing than
function expressions, which require you to use both the
var and function keywords.
Functions93
Page 94
Function statements provide a more consistent experience between the two compiler modes in
that you can use dot syntax in both strict and standard mode to invoke a method declared
using a function statement. This is not necessarily true for methods declared with a function
expression. For example, the following code defines a class named Example with two
methods:
methodStatement(), which is declared with a function statement. In strict mode, you cannot
use dot syntax to invoke the
class Example
{
var methodExpression = function() {}
function methodStatement() {}
}
var myEx:Example = new Example();
myEx.methodExpression(); // error in strict mode; okay in standard mode
myEx.methodStatement(); // okay in strict and standard modes
methodExpression(), which is declared with a function expression, and
methodExpression() method.
Function expressions are considered better suited to programming that focuses on run-time,
or dynamic, behavior. If you prefer to use strict mode, but also need to call a method declared
with a function expression, you can use either of two techniques. First, you can call the
method using square brackets (
[]) instead of the dot (.) operator. The following method call
succeeds in both strict mode and standard mode:
myExample["methodLiteral"]();
Second, you can declare the entire class as a dynamic class. Although this allows you to call the
method using the dot operator, the downside is that you sacrifice some strict mode
functionality for all instances of that class. For example, the compiler does not generate an
error if you attempt to access an undefined property on an instance of a dynamic class.
There are some circumstances in which function expressions are useful. One common use of
function expressions is for functions that are used only once and then discarded. Another, less
common use is for attaching a function to a prototype property. For more information, see
“The prototype object” on page 144.
94ActionScript Language and Syntax
Page 95
There are two subtle differences between function statements and function expressions that
you should take into account when choosing which technique to use. The first difference is
that function expressions do not exist independently as objects with regard to memory
management and garbage collection. In other words, when you assign a function expression to
another object, such as an array element or an object property, you create the only reference to
that function expression in your code. If the array or object to which your function expression
is attached goes out of scope or is otherwise no longer available, you will no longer have access
to the function expression. If the array or object is deleted, the memory that the function
expression uses will become eligible for garbage collection, which means that the memory is
eligible to be reclaimed and reused for other purposes.
The following example shows that for a function expression, once the property to which the
expression is assigned is deleted, the function is no longer available. The class Test is dynamic,
which means that you can add a property named
expression. The
functionExp property is deleted, the function is no longer accessible.
dynamic class Test {}
var myTest:Test = new Test();
// function expression
myTest.functionExp = function () { trace("Function expression") };
myTest.functionExp(); // Function expression
delete myTest.functionExp;
myTest.functionExp(); // error
functionExp() function can be called with the dot operator, but once the
functionExp that holds a function
If, on the other hand, the function is first defined with a function statement, it exists as its
own object, and continues to exist even after you delete the property to which it is attached.
The
delete operator only works on properties of objects, so even a call to delete the function
stateFunc() itself does not work.
dynamic class Test {}
var myTest:Test = new Test();
// function statement
function stateFunc() { trace("Function statement") }
myTest.statement = stateFunc;
myTest.statement(); // Function statement
delete myTest.statement;
delete stateFunc; // no effect
stateFunc(); // Function statement
myTest.statement(); // error
Functions95
Page 96
The second difference between function statements and function expressions is that function
statements exist throughout the scope in which they are defined, including in statements that
appear before the function statement. Function expressions, by contrast, are defined only for
subsequent statements. For example, the following code successfully calls the
scopeTest()
function before it is defined:
statementTest(); // statementTest
function statementTest():void
{
trace("statementTest");
}
Function expressions are not available before they are defined, so the following code results in
a run-time error:
expressionTest(); // run-time error
var expressionTest:Function = function ()
{
trace("expressionTest");
}
Returning values from functions
To return a value from your function, use the return statement followed by the expression or
literal value that you want to return. For example, the following code returns an expression
representing the parameter:
function doubleNum(baseNum:int):int
{
return (baseNum * 2);
}
Notice that the return statement terminates the function, so that any statements below a
return statement will not be executed, as follows:
function doubleNum(baseNum:int):int {
return (baseNum * 2);
trace("after return"); // This trace statement will not be executed.
}
In strict mode, you must return a value of the appropriate type if you choose to specify a
return type. For example, the following code generates an error in strict mode because it does
not return a valid value:
function doubleNum(baseNum:int):int
{
trace("after return");
}
96ActionScript Language and Syntax
Page 97
Nested functions
You can nest functions, which means that functions can be declared within other functions. A
nested function is available only within its parent function unless a reference to the function is
passed to external code. For example, the following code declares two nested functions inside
the
When nested functions are passed to external code, they are passed as function closures, which
means that the function retains any definitions that are in scope when the function is defined.
For more information, see “Function closures” on page 104.
Function parameters
ActionScript 3.0 provides some functionality for function parameters that may seem novel for
programmers new to the language. Although the idea of passing parameters by value or
reference should be familiar to most programmers, the
parameter may be new to many of you.
arguments object and the ... (rest)
Passing arguments by value or by reference
In many programming languages, it’s important to understand the distinction between
passing arguments by value or by reference; the distinction can affect the way code is
designed.
To be passed by value means that the value of the argument is copied into a local variable for
use within the function. To be passed by reference means that only a reference to the
argument is passed, instead of the actual value. No copy of the actual argument is made.
Instead, a reference to the variable passed as an argument is created and assigned to a local
variable for use within the function. As a reference to a variable outside the function, the local
variable gives you the ability to change the value of the original variable.
Functions97
Page 98
In ActionScript 3.0, all arguments are passed by reference because all values are stored as
objects. However, objects that belong to the primitive data types, which includes Boolean,
Number, int, uint, and String, have special operators that make them behave as if they were
passed by value. For example, the following code creates a function named
passPrimitives() that defines two parameters named xParam and yParam, both of type int.
These parameters are similar to local variables declared inside the body of the
passPrimitives() function. When the function is called with the arguments xValue and
yValue, the parameters xParam and yParam are initialized with references to the int objects
represented by
passed by value. Although
and
yValue objects, any changes to the variables within the function body generate new
xValue and yValue. Because the arguments are primitives, they behave as if
xParam and yParam initially contain only references to the xValue
copies of the values in memory.
function passPrimitives(xParam:int, yParam:int):void
{
Within the passPrimitives() function, the values of xParam and yParam are incremented,
but this does not affect the values of
xValue and yValue, as shown in the last trace
statement. This would be true even if the parameters were named identically to the variables,
xValue and yValue, because the xValue and yValue inside the function would point to new
locations in memory that exist separately from the variables of the same name outside the
function.
All other objects—that is, objects that do not belong to the primitive data types—are always
passed by reference, which gives you ability to change the value of the original variable. For
example, the following code creates an object named
The object is passed as an argument to the
passByRef() function. Because the object is not a
objVar with two properties, x and y.
primitive type, the object is not only passed by reference, but also stays a reference. This
means that changes made to the parameters within the function will affect the object
properties outside the function.
The objParam parameter references the same object as the global objVar variable. As you can
see from the
objParam object are reflected in objVar object.
trace statements in the example, changes to the x and y properties of the
Default parameter values
New in ActionScript 3.0 is the ability to declare default parameter values for a function. If a
call to a function with default parameter values omits a parameter with default values, the
value specified in the function definition for that parameter is used. All parameters with
default values must be placed at the end of the parameter list. The values assigned as default
values must be compile-time constants. The existence of a default value for a parameter
effectively makes that parameter an optional parameter. A parameter without a default value is
considered a required parameter.
For example, the following code creates a function with three parameters, two of which have
default values. When the function is called with only one parameter, the default values for the
parameters are used.
function defaultValues(x:int, y:int = 3, z:int = 5):void
{
trace(x, y, z);
}
defaultValues(1); // 1 3 5
The arguments object
When parameters are passed to a function, you can use the arguments object to access
information about the parameters passed to your function. Some important aspects of the
arguments object include the following:
■ The arguments object is an array that includes all the parameters passed to the function.
■ The arguments.length property reports the number of parameters passed to the
function.
■ The arguments.callee property provides a reference to the function itself, which is
useful for recursive calls to function expressions.
NOTE
The arguments object is not available if any parameter is named arguments or if you use
the ... (rest) parameter.
Functions99
Page 100
ActionScript 3.0 allows function calls to include more parameters than those defined in the
function definition, but will generate a compiler error in strict mode if the number of
parameters is less than the number of required parameters. You can use the array aspect of the
arguments object to access any parameter passed to the function, whether or not that
parameter is defined in the function definition. The following example uses the
array along with the
traceArgArray() function:
function traceArgArray(x:int):void
{
for (var i:uint = 0; i < arguments.length; i++)
{
trace(arguments[i]);
}
}
traceArgArray(1, 2, 3);
// output:
// 1
// 2
// 3
arguments.length property to trace all the parameters passed to the
arguments
The arguments.callee property is often used in anonymous functions to create recursion.
You can use it to add flexibility to your code. If the name of a recursive function changes over
the course of your development cycle, you need not worry about changing the recursive call in
your function body if you use
arguments.callee property is used in the following function expression to enable recursion:
var factorial:Function = function (x:uint)
{
if(x == 0)
{
return 1;
}
else
{
return (x * arguments.callee(x - 1));
}
}
arguments.callee instead of the function name. The
trace(factorial(5)); // 120
If you use the ... (rest) parameter in your function declaration, the arguments object will not
be available to you. Instead, you must access the parameters using the parameter names that
you declared for them.
100ActionScript Language and Syntax
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.