Macromedia FLEX-FLEX ACTIONSCRIPT LANGUAGE REFERENCE User Manual

Flex ActionScript Language Reference
Trademarks
ActiveEdit, ActiveTest, Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Blue Sky Software, Blue Sky, Breeze, Bright Tiger, Clustercats, ColdFusion, Contents Tab Composer, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, FlashHelp, Flash Lite, FlashPaper, Flex, Flex Builder, Fontographer, FreeHand, Generator, Help To Source, HomeSite, Hotspot Studio, HTML Help Studio, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live Effects, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Central, Macromedia Flash, Macromedia M Logo and Design, Macromedia Spectra, Macromedia xRes Logo and Design, MacroModel, Made with Macromedia, Made with Macromedia Logo and Design, MAGIC Logo and Design, Mediamaker, Movie Critic, Open Sesame!, RoboDemo, RoboEngine JFusion, RoboHelp, RoboHelp Office, RoboInfo, RoboInsight, RoboPDF, 1-Step RoboPDF, RoboFlash, RoboLinker, RoboScreenCapture, ReSize, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, Smart Publishing Wizard, Software Video Camera, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, WinHelp, WinHelp 2000, WinHelp BugHunter, WinHelp Find+, WinHelp Graphics Locator, WinHelp Hyperviewer, WinHelp Inspector, and Xtra are either registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions including internationally.
Third-Party Information
This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
Opera ® browser Copyright © 1995-2002 Opera Software ASA and its suppliers. All rights reserved.
Copyright © 2004 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced, translated, or converted to any electronic or machine-readable form in whole or in part without prior written approval of Macromedia, Inc. Part Number ZFE15M200
Acknowledgments
Project Management: Barbara Herbert, Stephen Gilson
Writing: Jody Bleyle, Mary Burger, Kim Diezel, Stephen Gilson, Stephanie Gowin, Dan Harris, Barbara Herbert, Matt Horn, Barbara Nelson, Shirley Ong, Michael Peterson, Tim Statler
Managing Editor: Rosana Francescato
Editing: Linda Adler, Mary Ferguson, Mary Kraemer, Noreen Maher, Antonio Padial, Lisa Stanziano, Anne Szabla
Production Management: Patrice O’Neill
Media Design and Production: Adam Barnett, Christopher Basmajian, Aaron Begley, John Francis
Second Edition: November 2004 Macromedia, Inc.
600 Townsend St. San Francisco, CA 94103

CONTENTS

INTRODUCTION: Getting Started with ActionScript . . . . . . . . . . . . . . . . . . . . . . . 5
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Using the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Terms used in this document. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
PART I: Welcome to ActionScript
CHAPTER 1: ActionScript Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Differences between ActionScript and JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . 10
Unicode support for ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
About data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Assigning data types to elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
About variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Using operators to manipulate values in expressions . . . . . . . . . . . . . . . . . . . . . . . 31
Using condition statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Using built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Creating functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
CHAPTER 2: Creating Custom Classes with ActionScript 2.0 . . . . . . . . . . . . . . . 45
Principles of object-oriented programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Using classes: a simple example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Creating and using classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Creating dynamic classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Using packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Creating and using interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Instance and class members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Implicit getter/setter methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Understanding the classpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Importing classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3
CHAPTER 3: Working with External Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Sending and loading variables to and from a remote source . . . . . . . . . . . . . . . . . . 67
Sending messages to and from Flash Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
PART II: Reference
CHAPTER 4: About the ActionScript Language Reference . . . . . . . . . . . . . . . . . 77
Sample entry for most ActionScript elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Sample entry for classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
CHAPTER 5: ActionScript Core Language Elements . . . . . . . . . . . . . . . . . . . . . . 80
CHAPTER 6: ActionScript Core Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
CHAPTER 7: ActionScript for Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
APPENDIX A: Deprecated Flash 4 operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
APPENDIX B: Keyboard Keys and Key Code Values . . . . . . . . . . . . . . . . . . . . . 811
Letters A to Z and standard numbers 0 to 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
Keys on the numeric keypad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
Function keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
Other keys. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817
INDEX OF LANGUAGE ELEMENTS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
4 Contents

INTRODUCTION

Getting Started with ActionScript

Macromedia Flex developers can use ActionScript to extend the functionality of their Flex applications. ActionScript is an ECMAScript-based language that provides support for object­oriented development. You are not required to use ActionScript to use Flex, but it provides flow control and object manipulation features that are not available in strict MXML.

Intended audience

This manual assumes that you already installed Macromedia Flex and know how to use it. If you have written programs before, ActionScript will seem familiar. But if you’re new to programming, ActionScript isn’t hard to learn. It’s easy to start with simple commands and build more complexity as you progress.

Using the documentation

This manual provides an overview of ActionScript syntax, information on how to use ActionScript when working with different types of objects, and details on the syntax and usage of every language element. The following list summarizes the contents of this manual.
Chapter 1, “ActionScript Basics,” on page 9 describes the terminology and basic concepts used
in the rest of the manual.
Chapter 2, “Creating Custom Classes with ActionScript 2.0,” on page 45 describes how to
create custom classes and objects for manipulating data in your applications.
Chapter 3, “Working with External Data,” on page 67 describes how to process data from
external sources using server- or client-side scripts in your applications.
Chapter 4, “About the ActionScript Language Reference,” on page 77 provides an overview of
the second part of the manual, which describes the elements that comprise the ActionScript language.
Chapter 5, “ActionScript Core Language Elements,” on page 80 explains all of the elements of
the ActionScript language that are not related to a particular class or to a particular Macromedia product.
Chapter 6, “ActionScript Core Classes,” on page 232 documents all of the classes of the
ActionScript language that are not related to a particular Macromedia product.
5
Chapter 7, “ActionScript for Flash,” on page 490 describe functions, properties, and classes of
Macromedia Flash Player that you can use in a Macromedia Flex application, if appropriate.
Appendix A, “Deprecated Flash 4 operators,” on page 809 lists all the ActionScript operators
and their associativity.
Appendix B, “Keyboard Keys and Key Code Values,” on page 811 lists all the keys on a
standard keyboard and the corresponding ASCII key code values that are used to identify the keys in ActionScript.

Typographical conventions

The following typographical conventions are used in this manual:
Code font indicates ActionScript code.
Code font italic indicates an element, such as an ActionScript parameter or object name,
that you replace with your own text when writing a script.

Terms used in this document

The following terms are used in this manual:
You refers to the developer who is writing a script or application.
The user refers to the person who is running your scripts and applications.
Compile time is the time at which you publish, export, test, or debug your document.
Runtime is the time at which your script is running in Flash Player.
ActionScript terms such as method and object are defined in Chapter 1, “ActionScript Basics,” on
page 9.

Additional resources

Specific documentation about Macromedia Flash and related products is available separately.
For information about creating communication applications with Flash Communication
Server, see Developing Communications Applications and Managing Flash Communication Server.
For information about building Flex applications, see Developing Flex Applications.
The Macromedia DevNet website (www.macromedia.com/devnet) is updated regularly with the latest information on Flash, plus advice from expert users, advanced topics, examples, tips, and other updates. Check the website often for the latest news on Flash and how to get the most out of the program.
The Macromedia Flash Support Center (www.macromedia.com/support/flash) provides TechNotes, documentation updates, and links to additional resources in the Flash community.
6 Introduction: Getting Started with ActionScript
PART I

Welcome to ActionScript

This part includes information on using the ActionScript language. For information on the classes and language elements you can use in your scripts, see Part II, “Reference.”
Chapter 1: ActionScript Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Chapter 2: Creating Custom Classes with ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Chapter 3: Working with External Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
PART I
CHAPTER 1

ActionScript Basics

ActionScript has rules of grammar and punctuation that determine which characters and words are used to create meaning and in which order they can be written. For example, in English, a period ends a sentence; in ActionScript, a semicolon ends a statement.
The general rules described in this section apply to all ActionScript. Most ActionScript terms also have individual requirements; for the rules for a specific term, see its entry in Part II, “Reference.”
Applying the basics of ActionScript in a way that creates elegant programs can be a challenge for users who are new to ActionScript.
This section contains the following topics:
“Differences between ActionScript and JavaScript” on page 10
“Terminology” on page 11
“Syntax” on page 13
“About data types” on page 18
“Assigning data types to elements” on page 23
“About variables” on page 27
“Using operators to manipulate values in expressions” on page 31
“Using condition statements” on page 39
“Using built-in functions” on page 41
“Creating functions” on page 41
9

Differences between ActionScript and JavaScript

ActionScript is similar to the core JavaScript programming language. You don’t need to know JavaScript to use and learn ActionScript; however, if you know JavaScript, ActionScript will seem familiar.
This manual does not attempt to teach general programming. There are many resources that provide more information about general programming concepts and the JavaScript language.
The European Computers Manufacturers Association (ECMA) document ECMA-262 is
derived from JavaScript and serves as the international standard for the JavaScript language. ActionScript is based on the ECMA-262 specification. For more information, see www.ecma-
international.org/publications/standards/Ecma-262.htm.
Netscape DevEdge Online has a JavaScript Developer Central site (http://
developer.netscape.com/tech/javascript/index.html) that contains documentation and articles
useful for understanding ActionScript. The most valuable resource is the Core JavaScript Guide.
The Java Technology site has tutorials on object-oriented programming (http://java.sun.com/
docs/books/tutorial/java/index.html) that are targeted for the Java language but are useful for
understanding concepts that you can apply to ActionScript.
Some of the differences between ActionScript and JavaScript are described in the following list:
ActionScript does not support browser-specific objects such as Document, Window,
and Anchor.
ActionScript does not completely support all the JavaScript built-in objects.
ActionScript does not support some JavaScript syntax constructs, such as statement labels.
In ActionScript, the eval() function can perform only variable references.
ActionScript2.0 supports several features that are not in the ECMA-262 specification, such as
classes and strong typing. Many of these features are modeled after the ECMAScript 4 Draft Proposal currently in development by ECMA TC39-TG1 (see www.mozilla.org/js/language/
es4/index.html), the standards committee in charge of the evolution of the ECMA-262
specification.
ActionScript does not support regular expressions using the RegExp object. However,
Macromedia Central does support the RegExp object.

Unicode support for ActionScript

Macromedia Flex supports Unicode text encoding for ActionScript. This means that you can include text in different languages in an ActionScript file. For example, you can include text in English, Japanese, and French in the same file. For more information on Unicode support in Flex, see “Using MXML” in Developing Flex Applications.
10 Chapter 1: ActionScript Basics

Terminology

As with all scripting languages, ActionScript uses its own terminology. The following list provides an introduction to important ActionScript terms:
Boolean is a true or false value.
Classes are data types that you can create to define a new type of object. To define a class,
you use the
Constants are elements that don’t change. For example, the constant Key.TAB always has the
same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values.
Constructors are functions that you use to define (initialize) the properties and methods of a
class. By definition, constructors are functions within a class definition that have the same name as the class. For example, the following code defines a Circle class and implements a constructor function:
// file Circle.as class Circle {
private var circumference:Number;
// constructor
function Circle(radius:Number){
}
}
The term constructor is also used when you create (instantiate) an object based on a particular class. The following statements are calls to the constructor functions for the built-in Array class and the custom Circle class:
var my_array:Array = new Array(); var my_circle:Circle = new Circle(9);
Data types
built-in ActionScript data types are String, Number, Boolean, Object, MovieClip, Function, null, and undefined. For more information, see “About data types” on page 18.
Events are actions that occur while a SWF file is playing. For example, different events are
generated when a movie clip loads, the user clicks a button or movie clip, or the user types on the keyboard.
Event handlers are special actions that manage events such as mouseDown or load. There are two
kinds of ActionScript event handlers: event handler methods and event listeners. Some commands can be used both as event handlers and as event listeners and are included in both subcategories. For more information on event management, see Developing Flex Applications.
Expressions are any legal combination of ActionScript symbols that represent a value. An
expression consists of operators and operands. For example, in the expression operands and
class keyword in a script file.
this.circumference = 2 * Math.PI * radius;
describe the kind of information a variable or ActionScript element can contain. The
x + 2, x and 2 are
+ is an operator.
Functions are blocks of reusable code that can be passed parameters and can return a value. For
more information, see “Creating functions” on page 41.
Terminology 11
Identifiers are names used to indicate a variable, property, object, function, or method. The first
character must be a letter, underscore ( letter, number, underscore, or dollar sign. For example,
Instances are objects that contain all the properties and methods of a particular class. For
_), or dollar sign ($). Each subsequent character must be a
firstName is the name of a variable.
example, all arrays are instances of the Array class, so you can use any of the methods or properties of the Array class with any array instance.
Instance names are unique names that let you target instances you create. For example, in the
following code, “names” and “studentName” are instance names for two objects, an array and a string:
var names:Array = new Array(); var studentName:String = new String();
Keywords
declare local variables. You cannot use a keyword as an identifier. For example,
are reserved words that have special meaning. For example, var is a keyword used to
var is not a legal
variable name. For a list of keywords, see “Keywords and reserved words” on page 17.
Methods are functions associated with a class. For example, sortOn() is a built-in method
associated with the Array class. You can also create functions that act as methods, either for objects based on built-in classes or for objects based on classes that you create. For example, in the following code,
clear() becomes a method of a controller object that you have previously
defined:
function reset(){
this.x_pos = 0;
this.y_pos = 0; } controller.clear = reset; controller.clear();
The following examples show how you create methods of a class:
//ActionScript 1 example A = new Object(); A.prototype.myMethod = function() {
trace("myMethod"); }
//ActionScript 2 example class B {
function myMethod() {
trace("myMethod");
} }
Objects
are collections of properties and methods; each object has its own name and is an instance of a particular class. Built-in objects are predefined in the ActionScript language. For example, the built-in Date class provides information from the system clock.
Operators are terms that calculate a new value from one or more values. For example, the
addition (
+) operator adds two or more values together to produce a new value. The values that
operators manipulate are called operands.
12 Chapter 1: ActionScript Basics
Parameters (also called arguments) are placeholders that let you pass values to functions.
For example, the following
firstName and hobby:
function welcome(firstName:String, hobby:String):String {
var welcomeText:String = "Hello, " + firstName + ". I see you enjoy " + hobby
+".";
return welcomeText;
}
Packages
are directories that contain one or more class files and reside in a designated classpath
welcome() function uses two values it receives in the parameters
directory (see “Understanding the classpath” on page 64).
Properties are attributes that define an object. For example, length is a property of all arrays that
specifies the number of elements in the array.
Statements are language elements that perform or specify an action. For example, the return
statement returns a result as a value of the function in which it executes. The evaluates a condition to determine the next action that should be taken. The
if statement
switch statement
creates a branching structure for ActionScript statements.
Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a
SWF file. You can use a target path to direct an action at a movie clip or to get or set the value of a variable or property. For example, the following statement is the target path to the property of the object named
stereoControl.volume
Variables
are identifiers that hold values of any data type. Variables can be created, changed, and
stereoControl:
volume
updated. The values they store can be retrieved for use in scripts. In the following example, the identifiers on the left side of the equal signs are variables:
var x:Number = 5; var name:String = "Lolo"; var c_color:Color = new Color(mcinstanceName);
For more information on variables, see “About variables” on page 27.

Syntax

As with all scripting languages, ActionScript has syntax rules that you must follow to create scripts that can compile and run correctly. This section describes the elements that comprise ActionScript syntax:
“Case sensitivity” on page 14
“Dot syntax” on page 14
“Curly braces” on page 15
“Semicolons” on page 15
“Parentheses” on page 16
“Comments” on page 16
Syntax 13
“Keywords and reserved words” on page 17
“Constants” on page 18

Case sensitivity

In a case-sensitive programming language, variable names that differ only in case ( are considered different from each other. Therefore, it’s good practice to follow consistent capitalization conventions, such as those used in this manual, to make it easy to identify names of functions and variables in ActionScript code.
Keywords, class names, variables, method names, and so on are case sensitive. For example:
// Sets properties of two different objects cat.hilite = true; CAT.hilite = true;
// Creates three different variables var myVar:Number=10; var myvar:Number=10; var mYvAr:Number=10;
This change also affects external variables loaded with LoadVars.load().
Case-sensitivity is implemented for external scripts, such as class files, scripts that you import using the
#include command, and scripts in a FLA file. If you encounter runtime errors and are
exporting to more than one version of Flash Player, you should review both external script files and scripts in FLA files to confirm that you used consistent capitalization.
Case-sensitivity is implemented on a per-movie basis. If a strict Flash Player 7 application calls a non-strict Flash Player 6 movie, ActionScript executed in the latter movie is non-strict. For example, if you use
loadMovie() to load a Flash Player 6 SWF into a Flash Player 7 SWF, the
version 6 SWF remains case-insensitive, while the version 7 SWF is treated as case-sensitive.
book and Book)

Dot syntax

In ActionScript, a dot (
.) is used to access properties or methods belonging to an object. It is also
used to identify the target path to a variable, function, or object. A dot syntax expression begins with the name of the object followed by a dot and ends with the element you want to specify.
For example, the
ball_mc._x refers to the _x property of the movie clip instance ball_mc.
Expressing a method of an object follows the same pattern. For example, the the
ball object would be called as follows:
ball.bounce();
_x movie clip property indicates a movie clip’s x axis position. The expression
bounce() method of
For more information, see _parent, _global object, and _root.
14 Chapter 1: ActionScript Basics

Curly braces

ActionScript event handlers, class definitions, and functions are grouped together into blocks with curly braces (
{}). You can put the opening brace on the same line as your declaration or on
the next line, as shown in the following examples. To make your code easier to read, it’s a good idea to choose one format and use it consistently. The following examples show the opening brace on same line as the declaration:
// Event handler my_btn.onRelease = function() {
var myDate:Date = new Date(); var currentMonth:Number = myDate.getMonth();
};
// Class Circle.as class Circle(radius) { }
// Function circleArea = function(radius:Number){
return radius * radius * Math.PI;
}
The following examples show code with opening brace on the next line:
//Event handler my_btn.onRelease = function() {
var myDate:Date = new Date(); var currentMonth:Number = myDate.getMonth();
};
//Class Square.as class Square(side) { }
//Function squareArea = function(side:Number) {
return side * side;
}

Semicolons

An ActionScript statement is terminated with a semicolon (
;), as shown in the following
examples:
var column:Number = passedDate.getDay(); var row:Number = 0;
If you omit the terminating semicolon, Flash still compiles your script successfully. However, it is good scripting practice to use semicolons because it makes your code more readable.
Syntax 15
Semicolons are required within for loops, as shown in the following example:
//For loop that adds numbers 1-10 var sum:Number = 0; for (var i=1; i<=10; i++) {
sum += i;
}

Parentheses

When you define a function, place any parameters inside parentheses [()]:
function myFunction (name:String, age:Number, reader:Boolean){
// your code here
}
When you call a function, include any parameters passed to the function in parentheses, as shown in the following example:
myFunction ("Steve", 10, true);
You can also use parentheses to override the ActionScript order of precedence or to make your ActionScript statements easier to read. (See “Operator precedence and associativity” on page 32.)
You also use parentheses to evaluate an expression on the left side of a dot (.) in dot syntax. For example, in the following statement, the parentheses cause
new Color(this) to evaluate and
create a Color object:
(new Color(this)).setRGB(0xffffff);
If you don’t use parentheses, you must add a statement to evaluate the expression, as shown in the following example:
myColor = new Color(this); myColor.setRGB(0xffffff);

Comments

Using comments to add notes to scripts is highly recommended. Comments are useful for tracking what you intended and for passing information to other developers if you work in a collaborative environment or are providing samples. Even a simple script is easier to understand if you make notes as you create it.
As shown in the following example, to indicate that a line or portion of a line is a comment, precede the comment with two forward slashes (
my_btn.onRelease = function() {
// create new Date object var myDate:Date = new Date(); var currentMonth:Number = myDate.getMonth(); // convert month number to month name var monthName:String = calcMonth(currentMonth); var year:Number = myDate.getFullYear(); var currentDate:Number = myDate.getDate();
};
16 Chapter 1: ActionScript Basics
//):
Comments can be any length without affecting the size of the exported file, and they do not need to follow rules for ActionScript syntax or keywords.
To create a comment block, place
/* at the beginning of the commented lines and */ at the end.
This technique lets you create lengthy comments without adding // at the beginning of each line.
By placing large chunks of script in a comment block, called commenting out a portion of your script, you can test specific parts of a script. For example, when the following script runs, none of the code in the comment block is executed:
// The following code runs var x:Number = 15; var y:Number = 20; // The following code doesn’t run /* // create new Date object var myDate:Date = new Date(); var currentMonth:Number = myDate.getMonth(); // convert month number to month name var monthName:String = calcMonth(currentMonth); var year:Number = myDate.getFullYear(); var currentDate:Number = myDate.getDate();} */ // The code below runs var name:String = "My name is"; var age:Number = 20;

Keywords and reserved words

ActionScript reserves words for specific use within the language, so you can’t use them as identifiers, such as variable, function, or label names. The following table lists all ActionScript keywords:
break case class continue
default delete dynamic else
extends for function get
if implements import in
instanceof interface intrinsic new
private public return set
static switch this typeof
var void while with
Syntax 17

Constants

A constant is a property whose value never changes. ActionScript contains predefined constants.
For example, the constants and refer to keyboard keys. To test whether the user is pressing the Enter key, you could use the following statement:
if(Key.getCode() == Key.ENTER) {
alert = "Are you ready to play?"; control_mc.gotoAndStop(5);
}
Flash does not enforce constants; that is, you can’t define your own constants.
BACKSPACE, ENTER, SPACE, and TAB are properties of the Key object

About data types

A data type describes a piece of data and the kinds of operations that can be performed on it. That data is stored in a variable. You use data types when creating variables, object instances, and function definitions.
ActionScript has the following basic data types that you will probably use frequently in your applications:
“String data type” on page 19
“Number data type” on page 19
“Boolean data type” on page 20
“Object data type” on page 21
“Null data type” on page 22
“Undefined data type” on page 23
“Void data type” on page 23
ActionScript also has built-in classes, such as Array and Date, that can be considered complex data types. If you are an advanced developer, you might create custom classes. Any class that you define using the
Variables containing primitive data types behave differently in certain situations than those containing reference types. (See “Using variables in a program” on page 29.) There are also two special data types: null and undefined.
When you debug scripts, you might need to determine the data type of an expression or variable to understand why it is behaving a certain way. You can do this with the (see “Determining an item’s data type” on page 26).
You can convert one data type to another using one of the following conversion functions:
Array(), Boolean(), Number(), Object(), String().
In ActionScript 2.0, you can assign data types to variables when you initialize them. The data types you assign can be any of the built-in types or can represent a custom class that you’ve created. For more information, see “Strict data typing” on page 24.
For more information on Flex data types, see Developing Flex Applications.
18 Chapter 1: ActionScript Basics
class declaration is also considered a data type.
instanceof operator

String data type

A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single (') or double (") quotation marks.
A common way that you use the string type is to assign a string to a variable. For example, in the following statement,
var favoriteBand_str:String = "L7";
"L7" is a string assigned to the variable favoriteBand_str:
You can use the addition (+) operator to concatenate, or join, two strings. ActionScript treats spaces at the beginning or end of a string as a literal part of the string. The following expression includes a space after the comma:
var greeting_str:String = "Welcome, " + firstName;
To include a quotation mark in a string, precede it with a backslash character (\). This is called escaping a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. The following table provides all the ActionScript escape characters:
Escape sequence Character
\b
\f
\n
\r
\t
\"
\'
\\
\000 - \377
\x00 - \xFF
\u0000 - \uFFFF
Backspace character (ASCII 8)
Form-feed character (ASCII 12)
Line-feed character (ASCII 10)
Carriage return character (ASCII 13)
Tab character (ASCII 9)
Double quotation mark
Single quotation mark
Backslash
A byte specified in octal
A byte specified in hexadecimal
A 16-bit Unicode character specified in hexadecimal
Strings in ActionScript are immutable, the same as Java. Any operation that modifies a string returns a new string.
The String class is a built-in ActionScript class.

Number data type

The number data type is a double-precision floating-point number. The minimum value of a number object is approximately 5e-324. The maximum is approximately 1.79E+308.
You can manipulate numbers using the arithmetic operators addition ( multiplication (
*), division (/), modulo (%), increment (++), and decrement (--). For more
+), subtraction (-),
information, see “Numeric operators” on page 33.
About data types 19
You can also use methods of the built-in Math and Number classes to manipulate numbers. For more information on the methods and properties of these classes, see the “Math class” and
“Number class” entries.
The following example uses the
sqrt() (square root) method of the Math class to return the
square root of the number 100:
Math.sqrt(100);
The following example traces a random integer between 10 and 17 (inclusive):
var bottles:Number = 0; bottles = 10 + Math.floor(Math.random()*7); trace("There are " + bottles + " bottles");
The following example finds the percent of the intro_mc movie clip loaded and represents it as an integer:
var percentLoaded:Number = Math.round((intro_mc.getBytesLoaded()/
intro_mc.getBytesTotal())*100);

Boolean data type

A Boolean value is one that is either and
false to 1 and 0 when appropriate. Boolean values are most often used with logical
true or false. ActionScript also converts the values true
operators in ActionScript statements that make comparisons to control the flow of a script.
The following example checks that users enter values into two TextInput component instances. Two Boolean variables are created, variables evaluate to
//Add two TextInput components and one Button component on the Stage //Strict data type the three component instances var userName_ti:mx.controls.TextInput; var password_ti:mx.controls.TextInput; var submit_button:mx.controls.Button;
true, a welcome message is assigned to the titleMessage String variable.
userNameEntered and isPasswordCorrect, and if both
//Create a listener object, which is used with the Button component //When the Button is clicked, checks for a user name and password var btnListener:Object = new Object(); btnListener.click = function(evt:Object) {
//checks that the user enters at least one character in the TextInput //instances and returns a Boolean true/false. var userNameEntered:Boolean = (userName_ti.text.length>0); var isPasswordCorrect:Boolean = (password_ti.text == "vertigo"); if (userNameEntered && isPasswordCorrect) {
var titleMessage:String = "Welcome "+userName_ti.text+"!";
} }; submit_button.addEventListener("click", btnListener);
For more information, see “Using built-in functions” on page 41 and “Logical operators”
on page 36.
20 Chapter 1: ActionScript Basics

Object data type

An object is a collection of properties. Each property has a name and a value. The value of a property can be any Flash data type—even the object data type. This lets you arrange objects inside each other, or nest them. To specify objects and their properties, you use the dot ( operator. For example, in the following code, is a property of
employee.weeklyStats.hoursWorked
employee:
hoursWorked is a property of weeklyStats, which
You can also create custom objects to organize information in your Flash application. To add interactivity to an application with ActionScript, you need many pieces of information: for example, you might need a user’s name, age, and phone number; the speed of a ball; the names of items in a shopping cart; or the key that was pressed last. Creating custom objects lets you organize this information into groups, simplify your scripting, and reuse your scripts.
The following ActionScript code shows an example of using custom objects to organize information. It creates a new object called
user and creates three properties: name, age and phone
which are String and Numeric data types.
var user:Object = new Object(); user.name = "Irving"; user.age = 32; user.phone = "555-1234";
For more information, see “Using classes: a simple example” on page 48.

MovieClip data type

Movie clips are symbols that can play animation in a Flash application. They are the only data type that refers to a graphic element. The MovieClip data type lets you control movie clip symbols using the methods of the MovieClip class.
You do not use a constructor to call the methods of the MovieClip class. You can create a movie clip instance on the Stage or create an instance dynamically. Then you simply call the methods of the MovieClip class using the dot (
Working with movie clips on the Stage. The following example calls the startDrag() and getURL() methods for different movie clip instances that are on the Stage:
my_mc.startDrag(true); parent_mc.getURL("http://www.macromedia.com/support/" + product);
.) operator.
The second example returns the width of a movie clip called my_mc on the Stage. The targeted instance must be a movie clip, and the returned value must be a numeric value.
function getMCWidth(target_mc:MovieClip):Number {
return target_mc._width; } trace(getMCWidth(my_mc));
.)
About data types 21
Creating movie clips dynamically Using ActionScript to create movie clips dynamically is
useful when you want to avoid manually creating movie clips on the Stage or attaching them from the library. For example, you might create an image gallery with a large number of thumbnails that you want to organize on the Stage. Using
MovieClip.createEmptyMovieClip() lets you
create an application entirely using ActionScript.
To dynamically create a movie clip, use
MovieClip.createEmptyMovieClip(), as shown in the
following example:
//Creates a movie clip to hold the container this.createEmptyMovieClip("image_mc", 9); //loads an image into image_mc image_mc.loadMovie("picture.jpg");
The second example creates a movie clip called square_mc that uses the Drawing API to draw a rectangle. Event handlers and the
startDrag() and stopDrag() methods of the MovieClip class
are added to make the rectangle draggable.
this.createEmptyMovieClip("square_mc", 1); square_mc.lineStyle(1, 0x000000, 100); square_mc.beginFill(0xFF0000, 100); square_mc.moveTo(100, 100); square_mc.lineTo(200, 100); square_mc.lineTo(200, 200); square_mc.lineTo(100, 200); square_mc.lineTo(100, 100); square_mc.endFill(); square_mc.onPress = function() {
this.startDrag(); }; square_mc.onRelease = function() {
this.stopDrag(); };
The MovieClip class is the base class for Flex components. Although Macromedia supports some of the MovieClip interface for use in Flex applications, much of the interface has been overridden by Flex. For more information on using the MovieClip class with Flex, see Developing Flex Applications.

Null data type

The null data type has only one value, You c an a ssi gn t he
null value in a variety of situations to indicate that a property or variable does
null. This value means no value—that is, a lack of data.
not yet have a value assigned to it. The following list shows some examples:
To indicate that a variable exists but has not yet received a value
To indicate that a variable exists but no longer contains a value
As the return value of a function, to indicate that no value was available to be returned by
the function
As a parameter to a function, to indicate that a parameter is being omitted
22 Chapter 1: ActionScript Basics
Several methods and functions return null if no value has been set. The following example demonstrates how you can use
if (Selection.getFocus() == null) {
trace("no selection"); }
null to test if form fields currently have form focus:

Undefined data type

The undefined data type has one value,
undefined, and is automatically assigned to a variable to
which a value hasn’t been assigned, either by your code or user interaction.
The value
undefined is automatically assigned; unlike null, you don’t assign undefined to a
variable or property. You use the undefined data type to check if a variable is set or defined. This data type lets you write code that executes only when the application is running, as shown in the following example:
if (init == undefined) {
trace("initializing app");
init = true; }
If your application has multiple frames, the code does not execute a second time because the init variable is no longer undefined.

Void data type

The void data type has one value,
void, and is used in a function definition to indicate that the
function does not return a value, as shown in the following example:
//Creates a function with a return type Void function displayFromURL(url:String):Void

Assigning data types to elements

At runtime, Flash Player automatically assigns data types to the following kinds of language elements, as discussed in the next section:
Variables
Parameters passed to a function, method, or class
Values returned from a function or method
Objects created as subclasses of existing classes
In ActionScript 2.0, you should explicitly assign data types to items, which can help prevent or diagnose certain errors in your scripts at compile time and offers other benefits. This technique is called strict data typing.
For more information on assigning data types, see the following topics:
“Automatic data typing” on page 24
“Strict data typing” on page 24
Assigning data types to elements 23
“Casting objects” on page 25
“Determining an item’s data type” on page 26

Automatic data typing

If you do not explicitly define an item as holding either a number, a string, or another data type, Flash Player will, at runtime, try to determine the data type of an item when it is assigned. If you assign a value to a variable, as shown in the following example, Flash Player evaluates at runtime the element on the right side of the operator and determines that it is of the Number data type:
var x = 3;
A later assignment might change the type of x; for example, the statement x = "hello" changes the type of determine the type; to the compiler, the variable
typing” on page 24.)
ActionScript converts data types automatically when an expression requires it and the variables aren’t strictly typed.
For example, when you pass a value to the the value to a string and sends it to the log file.
In expressions with operators, ActionScript converts data types as needed; in the following example, when used with a string, the addition ( a string:
"Next in line, number " + 7
ActionScript converts the number 7 to the string "7" and adds it to the end of the first string, resulting in the following string:
"Next in line, number 7"
Strict data typing is recommended; for more information, see “Strict data typing” on page 24.
x to a string. Because x was not declared using strict data typing, the compiler cannot
x can have a value of any type. (See “Strict data
trace() statement, trace() automatically converts
+) operator expects the other operand to be

Strict data typing

ActionScript lets you explicitly declare the object type of a variable when you create it, which is called strict data typing. Strict data typing offers several benefits at compile time. Because data type mismatches trigger compiler errors, strict data typing helps you find bugs in your code at compile time and prevents you from assigning the wrong type of data to an existing variable. During authoring, strict data typing activates code hinting in the ActionScript editor (but you should still use instance-name suffixes for visual elements). Although strict data typing is relevant only at compile time, it can increase performance at runtime by making your scripts run faster.
To assign a specific data type to an item, specify its type using the
var keyword and post-colon
syntax, as shown in the following example:
// strict typing of variable or object var x:Number = 7; var birthday:Date = new Date();
// strict typing of parameters
24 Chapter 1: ActionScript Basics
function welcome(firstName:String, age:Number){ }
// strict typing of parameter and return value function square(x:Number):Number {
var squared:Number = x*x;
return squared; }
Because you must use the var keyword when strictly typing variable, you can’t strictly type a global variable (see “Scoping and declaring variables” on page 28).
You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and so on) and on classes and interfaces that you create. In the following example, if you have a file named Student.as in which you define the Student class, you can specify that objects you create are of type Student:
var student:Student = new Student();
You can also specify that objects are of type Function or Void.
Using strict data typing helps ensure that you don’t inadvertently assign an incorrect type of value to an object. Flash checks for typing mismatch errors at compile time. For example, suppose you type the following code:
// in the Student.as class file class Student {
var status:Boolean; // property of Student objects }
// in a script var studentMaryLago:Student = new Student(); studentMaryLago.status = "enrolled";
When Flash compiles this script, a “Type mismatch” error is generated because the SWF file is expecting a Boolean value.
Using strict typing also helps to ensure that you do not attempt to access properties or methods that are not part of an object’s type.

Casting objects

ActionScript lets you cast one data type to another. The cast operator that Flash uses takes the form of a function call and is concurrent with explicit coercion, as specified in the ECMA-262 Edition 4 proposal (see www.mozilla.org/js/language/es4/index.html). Casting lets you assert that an object is of a certain type so that when type-checking occurs, the compiler treats the object as having a set of properties that its initial type does not contain. This can be useful, for example, when iterating over an array of objects that might be of differing types but share a base type.
Assigning data types to elements 25
The syntax for casting is type(item), where you want the compiler to behave as if the data type of
item is type. Casting is essentially a function call, and the function call returns null if the cast
fails at runtime. If the cast succeeds, the function call returns the original object. However, the compiler cannot determine whether a cast will fail at runtime and won’t generate compile-time errors in those cases. The following code shows an example:
function bark(myAnimal:Animal) { var foo:Dog = Dog(myAnimal); foo.bark(); }
var curAnimal:Animal = new Dog(); bark(curAnimal); // will work curAnimal = new Cat(); bark(curAnimal); // won't work
In this situation, you asserted to the compiler that foo is a Dog object, and, therefore, the compiler assumes that
temp.bark(); is a legal statement. However, the compiler doesn’t know
that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no compile­time error occurs. If you include a check in your script to make sure that the cast succeeds, you can find casting errors at runtime.
import Dog; function bark(myAnimal:Animal) {
var foo:Dog = Dog(myAnimal);
if (foo) {
foo.bark();
} }
You can cast an expression to an interface. If the expression is an object that implements the interface or has a base class that implements the interface, the cast succeeds. If not, the cast fails.
Casting to null or undefined returns
undefined.
You can’t override primitive data types that have a corresponding global conversion function with a cast operator of the same name. This is because the global conversion functions have precedence over the cast operators. For example, you can’t cast to Array because the
Array() conversion
function takes precedence over the cast operator. For more information on data conversion functions, see
Array(), Boolean(), Number(), Object(), and String().

Determining an item’s data type

While testing and debugging your programs, you might discover problems that seem to be related to the data types of different items. In these cases, you may want to determine an item’s data type. You can use either the
Use the
typeof operator to get the data types; typeof does not return information about which
class to which an instance belongs. Use the specified data type or not;
26 Chapter 1: ActionScript Basics
typeof operator or the instanceof operator.
instanceof operator to determine if an object is of a
instanceof returns a Boolean value.
The following example shows how you can use these operators and the difference between them:
//Create a new instance of LoadVars class var myLV:LoadVars = new LoadVars();
//instanceof operator specifies instance of what class if (myLV instanceof LoadVars) {
trace("yes, it's a loadvars instance"); }
//typeof operator does not specify class, only specifies that myLV is an object var typeResult:String = typeof(myLV); trace(typeResult);

About variables

A variable is a container that holds information. The container itself is always the same, but the contents can change. By changing the value of a variable as the SWF file plays, you can record and save information about what the user has done, record values that change as the SWF file plays, or evaluate whether a condition is true or false.
It’s a good idea always to assign a variable a known value the first time you define the variable. This is known as initializing a variable. If a variable is declared in the FLA (instead of in an external file), it works only for the frame where the variable is declared. Only the frame code for that frame is scanned, so the second frame would not recognize the variable if it was referenced. Initializing a variable helps you track and compare the variable’s value as the SWF file plays.
Variables can hold any type of data (see “About data types” on page 18). The type of data a variable contains affects how the variable’s value changes when it is assigned in a script.
Typical types of information that you can store in a variable include a URL, a user’s name, the result of a mathematical operation, the number of times an event occurred, or whether a button has been clicked. Each SWF file and movie clip instance has a set of variables, with each variable having a value independent of variables in other SWF files or movie clips.
To view the value of a variable, use the example,
trace(hoursWorked) sends the value of the variable hoursWorked to the log file. You
trace() statement to send the value to the log file. For
can then review the log file to see if your variables are being set or changed as expected.
For more information, see the following topics:
“Naming a variable” on page 27
“Scoping and declaring variables” on page 28
“Using variables in a program” on page 29

Naming a variable

A variable’s name must follow these rules:
It must be an identifier (see “Terminology” on page 11).
It cannot be a keyword or an ActionScript literal such as true, false, null, or undefined.
It must be unique within its scope (see “Scoping and declaring variables” on page 28).
About variables 27
You should not use any element in the ActionScript language as a variable name because it can cause syntax errors or unexpected results. In the following example, if you name a variable and then try to create a String object using
// This code works as expected var hello_str:String = new String(); trace(hello_str.length); // returns 0
// But if you give a variable the same name as a built-in class....
var String:String = “hello”; var hello_str:String = new String(); trace(hello_str.length); // returns undefined
new String(), the new object is undefined:

Scoping and declaring variables

A variable’s scope refers to the area in which the variable is known and can be referenced. For example, local variables are available within the function body in which they are declared (delineated by curly braces [{}]), and global variables and functions are visible to every scope in your document. Local and global variables are discussed later in this section. For more information, see Developing Flex Applications.
Note: ActionScript classes that you create support public, private, and static variable scopes. For more information, see “Controlling member access” on page 53 and “Creating class members”
on page 60.
Local variables
To declare local variables, use the
var statement inside the body of a function. A local variable
declared within a function block is defined within the scope of the function block and expires at the end of the function block.
String
For example, the variables used as a local variable; it exists only inside the function
var myArray:Array = [ ]; function initArray(arrayLength:Number) {
var i:Number;
for( i = 0; i < arrayLength; i++ ) {
myArray[i] = i + 1;
} }
i and j are often used as loop counters. In the following example, i is
initArray():
Local variables can also help prevent name conflicts, which can cause errors in your application. For example, if you use
age as a local variable, you could use it to store a person’s age in one
context and the age of a person’s child in another; because these variables would run in separate scopes, there would be no conflict.
It’s good practice to use local variables in the body of a function so that the function can act as an independent piece of code. A local variable is changeable only within its own block of code. If an expression in a function uses a global variable, something outside the function can change its value, which would change the function.
28 Chapter 1: ActionScript Basics
You can assign a data type to a local variable when you define it, which helps prevent you from assigning the wrong type of data to an existing variable. For more information, see “Strict data
typing” on page 24.
Global variables
Global variables and functions are visible to every scope in your document. To create a variable with global scope, use the syntax. For example, the following code creates the global variable
var _global.myName = "George"; // incorrect syntax for global variable _global.myName = "George"; // correct syntax for global variable
_global identifier before the variable name and do not use the var =
myName:
However, if you initialize a local variable with the same name as a global variable, you don’t have access to the global variable while you are in the scope of the local variable, as shown in the following example:
_global.counter = 100; // declares global variable trace(counter); // accesses the global variable and displays 100 function count(){ for( var counter = 0; counter <= 2 ; counter++ ) { //local variable trace(counter); // accesses local variable and displays 0 through 2 } } count(); trace(counter); // accesses global variable and displays 100
This example simply shows that the global variable is not accessed in the scope of the count() function. To avoid confusion in your applications, name your variables uniquely.
The Flash Player version 7 and later security sandbox enforces restrictions when accessing global variables from movies loaded from separate security domains.

Using variables in a program

You must declare and initialize a variable in a script before you can use it in an expression. If you use an undeclared variable, as shown in the following example, the variable’s value will be
undefined, and your script might produce unintended results:
var squared:Number = x*x; trace(squared); // NaN var x:Number = 6;
In the following example, the statement declaring and initializing the variable x comes first, so
squared can be replaced with a value:
var x:Number = 6; var squared:Number = x*x; trace(squared); // 36
Similar behavior occurs when you pass an undefined variable to a method or function:
//does not work getURL(myWebSite); // no action var myWebSite = "http://www.macromedia.com"; //works
About variables 29
NaN or
var myWebSite = "http://www.macromedia.com"; getURL(myWebSite); // browser displays www.macromedia.com
You can change the value of a variable in a script as many times as you want.
The type of data that a variable contains affects how and when the variable’s value changes. Primitive data types, such as strings and numbers, are “passed by value”; this means that the current value of the variable is used, rather than a reference to that value.
In the following example, in line 3, the value of of
x that it received in line 2.
var x:Number = 15; var y:Number = x; var x:Number = 30; trace(x); // 30 trace(y); // 15
x is set to 15 and that value is copied into y. When x is changed to 30
y remains 15, because y doesn’t look to x for its value; it contains the value
In the following example, the variable inValue contains a primitive value, 3, so that value is passed to the
function sqr(x:Number):Number {
var x:Number = x * x;
return x; }
var inValue:Number = 3; var out:Number = sqr(inValue); trace(inValue); //3 trace(out); //9
sqr() function and the returned value is 9:
The value of the variable inValue does not change, even though the value of x in the function changes.
The object data type can contain such a large amount of complex information that a variable with this type doesn’t hold an actual value; it holds a reference to a value. This reference is similar to an alias that points to the contents of the variable. When the variable needs to know its value, the reference asks for the contents and returns the answer without transferring the value to the variable.
The following example shows passing by reference:
var myArray:Array = ["tom", "josie"]; var newArray:Array = myArray; myArray[1] = "jack"; trace(newArray); // tom,jack
This code creates an Array object called myArray that has two elements. The variable newArray is created and is passed a reference to "
jack", it affects every variable with a reference to it. The trace() statement sends tom,jack to
myArray. When the second element of myArray is changed to
the log file. Flash uses a zero-based index, which means that 0 is the first item in the array, 1 is the second, and so on.
30 Chapter 1: ActionScript Basics
In the following example, myArray contains an Array object, so it is passed to function
zeroArray() by reference. The function zeroArray() accepts an Array object as a parameter
and sets all the elements of that array to 0. It can modify the array because the array is passed by reference.
function zeroArray (theArray:Array):Void {
var i:Number;
for (i=0; i < theArray.length; i++) {
theArray[i] = 0;
} }
var myArray:Array = new Array(); myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; zeroArray(myArray); trace(myArray); // 0,0,0

Using operators to manipulate values in expressions

An expression is any statement that Flash can evaluate and that returns a value. You can create an expression by combining operators and values or by calling a function.
Operators are characters that specify how to combine, compare, or modify the values of an expression. The elements that the operator performs on are called operands. For example, in the following statement, the addition ( the variable
foo + 3
foo; foo and 3 are the operands:
+) operator adds the value of a numeric literal to the value of
This section describes general rules about common types of operators, operator precedence, and operator associativity:
“Operator precedence and associativity” on page 32
“Numeric operators” on page 33
“Comparison operators” on page 34
“String operators” on page 35
“Logical operators” on page 36
“Bitwise operators” on page 36
“Equality operators” on page 37
“Assignment operators” on page 37
“Dot and array access operators” on page 38
For detailed information on these operators as well as special operators that don’t fall into these categories, see Chapter 5, “ActionScript Core Language Elements,” on page 80.
Using operators to manipulate values in expressions 31

Operator precedence and associativity

When two or more operators are used in the same statement, some operators take precedence over others. ActionScript follows a precise hierarchy to determine which operators to execute first. For example, multiplication is always performed before addition; however, items in parentheses [()] take precedence over multiplication. So, without parentheses, ActionScript performs the multiplication in the following example first:
total = 2 + 4 * 3;
The result is 14.
But when parentheses surround the addition operation, ActionScript performs the addition first:
total = (2 + 4) * 3;
The result is 18.
When two or more operators share the same precedence, their associativity determines the order in which they are performed. Associativity can be either left-to-right or right-to-left. For example, the multiplication (*) operator has an associativity of left-to-right; therefore, the following two statements are equivalent:
total = 2 * 3 * 4; total = (2 * 3) * 4;
The following table lists all the ActionScript operators and their associativity, from highest to lowest precedence.
Operator Description Associativity
Highest precedence
x++
x--
.
[ ]
( )
function ( )
++x
--x
-
~
!
new
delete
typeof
void
Post-increment Left to right
Post-decrement Left to right
Object property access Left to right
Array element Left to right
Parentheses Left to right
Function call Left to right
Pre-increment Right to left
Pre-decrement Right to left
Unary negation, such as x = -1 Left to right
Bitwise NOT Right to left
Logical NOT Right to left
Allocate object Right to left
Deallocate object Right to left
Type of object Right to left
Returns undefined value Right to left
32 Chapter 1: ActionScript Basics
Operator Description Associativity
*
/
%
+
-
<<
>>
>>>
instanceof
Multiply Left to right
Divide Left to right
Modulo Left to right
Unary plus Right to left
Unary minus Right to left
Bitwise left shift Left to right
Bitwise right shift Left to right
Bitwise right shift (unsigned) Left to right
Instance of (finds the class of which the object is an
Left to right instance) Requires Flash Player 6 or later
<
<=
>
>=
==
!=
&
^
|
&&
||
?:
=
*=, /=, %=, +=, -
=, &=, |=, ^=, <<=, >>=, >>>=
,
Less than Left to right
Less than or equal to Left to right
Greater than Left to right
Greater than or equal to Left to right
Equal Left to right
Not equal Left to right
Bitwise AND Left to right
Bitwise XOR Left to right
Bitwise OR Left to right
Logical AND Left to right
Logical OR Left to right
Conditional Right to left
Assignment Right to left
Compound assignment Right to left
Comma Left to right
Lowest precedence

Numeric operators

Numeric operators add, subtract, multiply, divide, and perform other arithmetic operations.
The most common use of the increment operator is
i++ instead of the more verbose i = i+1.
You can use the increment operator before or after an operand. In the following example, incremented first and then tested against the number 30:
if (++age >= 30)
Using operators to manipulate values in expressions 33
age is
This process is also known as a preincrement. In the following example, age is incremented after the test is performed:
if (age++ >= 30)
This process is also known as a postincrement. The following table lists the ActionScript numeric operators:
Operator Operation performed
+
*
/
%
-
++
--
Addition
Multiplication
Division
Modulo (remainder of division)
Subtraction
Increment
Decrement

Comparison operators

Comparison operators compare the values of expressions and return a Boolean value (
false). These operators are most commonly used in loops and in conditional statements. In the
following example, if the variable
score is 100, a certain function is called; otherwise, a different
true or
function is called:
// call one function or another based on score if (score > 100){
highScore(); } else {
lowScore(); }
In the following example, if the user’s entry (a string variable, userEntry) matches their stored password, the playhead moves to a named frame called
if (userEntry == userPassword) { gotoAndStop("welcomeUser"); }
welcomeUser:
Except for the strict equality (==) operator, the comparison operators compare strings only if both operands are strings. If only one of the operands is a string, ActionScript converts both operands to numbers and performs a numeric comparison. Uppercase characters precede lowercase in alphabetic order, so “Eagle” comes before “dog.” If you want to compare two strings or characters regardless of case, you need to convert both strings to upper- or lowercase before comparing them.
34 Chapter 1: ActionScript Basics
The following table lists the ActionScript comparison operators:
Operator Operation performed
<
>
<=
>=
<> !=
== Equality: Tests two expressions for equality. The result is
=== Strict equality: Tests two expressions for equality; the strict equality operator performs
Less than: Returns true if the left operand is mathematically smaller than the right operand. Returns example, a < b).
Greater than: Returns true if the left operand is mathematically larger than the right operand.
Returns b > a).
Less than or equal to: Returns true if the left operand is mathematically smaller than or the same as the right operand. Returns operand.
Greater than or equal to: Returns true if the left operand is mathematically larger than or the same as the right operand. Returns operand.
Not equal: Returns Returns
equal.
the same as the equality operator except that data types are not converted. The result is strings.
true if the left operand alphabetically precedes the right operand (for
true if the left operand alphabetically follows the right operand (for example,
true if the left operand alphabetically precedes or is the same as the right
true if the left operand alphabetically follows or is the same as the right
true if the operands are not mathematically equivalent.
true if the operands are not the same.
true if the expressions are
true if both expressions, including their data types, are equal. Does not apply to

String operators

The addition (+) operator has a special effect when it operates on strings: It concatenates the two string operands. For example, the following statement adds
"Congratulations, " + "Donna!"
"Congratulations," to "Donna!":
The result is "Congratulations, Donna!" If only one of the addition (+) operator’s operands is a string, Flash converts the other operand to a string. ActionScript treats spaces at the beginning or end of a string as a literal part of the string.
The comparison operators
>, >=, <, and <= also have a special effect when operating on strings.
These operators compare two strings to determine which is first in alphabetical order. The comparison operators compare strings only if both operands are strings. If only one of the operands is a string, ActionScript converts both operands to numbers and performs a numeric comparison. Uppercase characters precede lowercase in alphabetic order, so “Eagle” comes before “dog.” If you want to compare two strings or characters regardless of case, you need to convert both strings to upper- or lowercase before comparing them.
Using operators to manipulate values in expressions 35

Logical operators

Logical operators compare Boolean values ( For example, if both operands evaluate to one or both of the operands evaluate to
true and false) and return a third Boolean value.
true, the logical AND (&&) operator returns true. If
true, the logical OR (||) operator returns true. Logical
operators are often used with comparison operators to determine the condition of an statement. For example, in the following script, if both expressions are true, the execute and the
if (i > 10 && i <50){
myFunc(i); }
myFunc() function will be called:
if statement will
Consider the order of operands, especially if you’re setting up complex conditions and you know how often one condition is true compared with other conditions. In the previous example, if you know that, in most cases, condition
i<50 will be checked first, and the second condition doesn’t need to be checked in most
i will be greater than 50, consider putting the condition i<50 first; the
cases.
The following table lists the ActionScript logical operators:
Operator Operation performed
&&
||
!operand Logical NOT: Returns the logical (Boolean) opposite of the operand. The logical NOT
Logical AND: Returns true only if both the left and right operands are true.
Logical OR: Returns true if either the left or right operand is true.
operator takes one operand.
if

Bitwise operators

Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers. The exact operation performed depends on the operator, but all bitwise operations evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value.
The following table lists the ActionScript bitwise operators:
Operator Operation performed
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<< Shift left
>> Shift right
>>> Shift right zero fill
36 Chapter 1: ActionScript Basics

Equality operators

You can use the equality ( operands are equal. This comparison returns a Boolean (
==) operator to determine whether the values or references of two
true or false) value. If the operands are
strings, numbers, or Boolean values, they are compared by value. If the operands are objects or arrays, they are compared by reference.
It is a common mistake to use the assignment operator to check for equality. For example, the following code compares x to 2:
if (x == 2)
In that same example, the expression if (x = 2) would be incorrect, because it doesn’t compare the operands; it assigns the value of 2 to the variable
The strict equality (
===) operator is similar to the equality operator, with one important
x.
difference: The strict equality operator does not perform type conversion. If the two operands are of different types, the strict equality operator returns
false. The strict inequality (!==) operator
returns the opposite of the strict equality operator.
The following table lists the ActionScript equality operators:
Operator Operation performed
==
===
!=
!==
Equality
Strict equality
Inequality
Strict inequality

Assignment operators

You can use the assignment (
=) operator to assign a value to a variable, as shown in the
following example:
var password:String = "Sk8tEr";
You can also use the assignment operator to assign multiple variables in the same expression. In the following statement, the value of
a = b = c = d;
d is assigned to the variables a, b, and c:
You can also use compound assignment operators to combine operations. Compound operators perform on both operands and then assign the new value to the first operand. For example, the following two statements are equivalent:
x += 15; x = x + 15;
The assignment operator can also be used in the middle of an expression, as shown in the following example:
// If the flavor is not vanilla, output a message. if ((flavor = getIceCreamFlavor()) != "vanilla") {
trace ("Flavor was " + flavor + ", not vanilla."); }
Using operators to manipulate values in expressions 37
This code is equivalent to the following code, which is slightly easier to read:
flavor = getIceCreamFlavor(); if (flavor != "vanilla") {
trace ("Flavor was " + flavor + ", not vanilla."); }
The following table lists the ActionScript assignment operators:
Operator Operation performed
=
+=
-=
*=
%=
/=
<<=
>>=
>>>=
^=
|=
&=
Assignment
Addition and assignment
Subtraction and assignment
Multiplication and assignment
Modulo and assignment
Division and assignment
Bitwise shift left and assignment
Bitwise shift right and assignment
Shift right zero fill and assignment
Bitwise XOR and assignment
Bitwise OR and assignment
Bitwise AND and assignment

Dot and array access operators

You can use the dot operator (
.) and the array access operator ([]) to access built-in or custom
ActionScript object properties.
Dot operator. The dot operator uses the name of an object on its left side and the name of a
property or variable on its right side. The property or variable name can’t be a string or a variable that evaluates to a string; it must be an identifier. The following examples use the dot operator:
year.month = "June"; year.month.day = 9;
The dot operator and the array access operator perform the same role, but the dot operator takes an identifier as its property, whereas the array access operator evaluates its contents to a name and then accesses the value of that named property.
For example, the following expressions access the same variable
rocket:
rocket.velocity; rocket["velocity"];
38 Chapter 1: ActionScript Basics
velocity in the movie clip
Array access operator. You can use the array access operator to dynamically set and retrieve
instance names and variables. For example, in the following code, the expression inside the array access operator is evaluated, and the result of the evaluation is used as the name of the variable to be retrieved from movie clip
name["mc" + i]
name:
In ActionScript 2.0, you can use the bracket operator to access dynamically created properties, if the dynamic keyword was not used to define the class, as shown in the following example:
class Foo { }
// in a fla that uses Foo var bar:Foo = new Foo(); function barGetProp():String { return "bar"; } function barSetProp(str:String):Void { } bar.addProperty("someProp", barGetProp, barSetProp); //trace(bar.someProp); // generates an error trace(bar["someProp"]); // no error
You can use the eval() function to dynamically set and retrieve instance names and variables, as shown in the following example:
eval("mc" + i)
The array access operator can also be used on the left side of an assignment statement. This lets you dynamically set instance, variable, and object names, as shown in the following example:
name[index] = "Gary";
You create multidimensional arrays in ActionScript by constructing an array, the elements of which are also arrays. To access elements of a multidimensional array, you can nest the array access operator with itself, as shown in the following example:
var chessboard:Array = new Array(); for (var i=0; i<8; i++) {
chessboard.push(new Array(8)); } function getContentsOfSquare(row, column){
chessboard[row][column]; }
When you use the array access operator, the ActionScript compiler cannot check if the accessed element is a valid property of the object.

Using condition statements

To perform an action depending on whether a condition exists, or to repeat an action (create loop statements), you can use statements.
if, else, else if, for, while, do while, for..in, or switch
Using condition statements 39
Checking conditions
Statements that check whether a condition is condition evaluates to
true, ActionScript executes the next statement. If the condition doesn’t
true or false begin with the term if. If the
exist, ActionScript skips to the next statement outside the block of code.
To optimize your code’s performance, check for the most likely conditions first.
The following statements test three conditions. The term
else if specifies alternative tests to
perform if previous conditions are false.
if (password == null || email == null) {
gotoAndStop("reject"); } else if (password == userID){
gotoAndPlay("startProgram"); }
If you want to check for one of several conditions, you can use the switch statement rather than multiple else if statements.
Repeating actions
ActionScript can repeat an action a specified number of times or while a specific condition exists. Use the
To repeat an action while a condition exists:
while, do..while, for, and for..in actions to create loops.
Use the while statement.
A
while loop evaluates an expression and executes the code in the body of the loop if the
expression is You can use the
do..while loop, the expression is evaluated at the bottom of the code block so the loop always
runs at least once.
true. After each statement in the body is executed, the expression is evaluated again.
do..while statement to create the same kind of loop as a while loop. In a
To repeat an action using a built-in counter:
Use the for statement.
Most loops use some kind of counter to control how many times the loop executes. Each execution of a loop is called an iteration. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. In the
for action, the counter and
the statement that increments the counter are part of the action. In the following example, the first expression ( second expression ( third expression (
for (var i = 4; i > 0; i--){
my_mc.duplicateMovieClip("newMC"+ i, i, {_x:i*20, _y:i*20}); }
To loop through the children of an object:
var i = 4) is the initial expression that is evaluated before the first iteration. The
i > 0) is the condition that is checked each time before the loop runs. The
i--) is called the post expression and is evaluated each time after the loop runs.
Use the for..in statement.
40 Chapter 1: ActionScript Basics
Children include other functions, objects, and variables. The following example uses the trace statement to print its results in the Output panel:
var myObject:Object = { name:'Joe', age:25, city:'San Francisco' }; for (propertyName in myObject) {
trace("myObject has the property: " + propertyName + ", with the value: " +
myObject[propertyName]); }
This example produces the following results in the Output panel:
myObject has the property: name, with the value: Joe myObject has the property: age, with the value: 25 myObject has the property: city, with the value: San Francisco
You might want your script to iterate over a particular type of child. You can do this using
for..in with the typeof operator.
for (myname in my_object) {
if (typeof (my_object[myname]) == "anObject") {
trace("I have an object child named " + myname);
} }
For more information on each action, see while, do while, for, for..in.

Using built-in functions

A function is a block of ActionScript code that can be reused anywhere in a SWF file. If you pass values as parameters to a function, the function will operate on those values. A function can also return values.
Flash has built-in functions that let you access certain information and perform certain tasks, such as getting the version number of Flash Player that is hosting the SWF file (
getVersion()).
Functions that belong to an object are called methods. Functions that don’t belong to an object are called top-level functions.
Each function has individual characteristics, and some functions require you to pass certain values. If you pass more parameters than the function requires, the extra values are ignored. If you don’t pass a required parameter, the empty parameters are assigned the
undefined data type,
which can cause errors during runtime.
To call a function, simply use the function name and pass any required parameters:
isNaN(someVar); getTimer(); eval("someVar");
For more information on each function, see its entry in Chapter 5, “ActionScript Core Language
Elements,” on page 80.

Creating functions

You can define functions to execute a series of statements on passed values. Your functions can also return values.
Creating functions 41
A well-written function can be thought of as a “black box.” If it has carefully placed comments about its input, output, and purpose, a user of the function does not need to understand exactly how the function works internally.
For more information, see the following topics:
“Defining a function” on page 42
“Passing parameters to a function” on page 42
“Using variables in a function” on page 43
“Returning values from a function” on page 43
“Calling a user-defined function” on page 44

Defining a function

As with variables, you can use the to all scopes without using a target path. To define a global function, precede the function name with the identifier
_global.myFunction = function (x:Number):Number { return (x*2)+3; }
_global, as shown in the following example:
You can also define a function by creating a function literal—an unnamed function that is declared in an expression instead of in a statement. You can use a function literal to define a function, return its value, and assign it to a variable in one expression, as shown in the following example:
area = (function() {return Math.PI * radius *radius;})(5);
When a function is redefined, the new definition replaces the old definition.
For information on strictly typing function return types and parameters, see “Strict data typing”
on page 24.
_global identifier to declare a global function that is available

Passing parameters to a function

Parameters are the elements on which a function executes its code. (In this manual, the terms parameter and argument are interchangeable.) For example, the following function takes the parameters
function fillOutScorecard(initials:String, finalScore:Number):Void {
scorecard.display = initials;
scorecard.score = finalScore; }
initials and finalScore:
When the function is called, the required parameters must be passed to the function. The function substitutes the passed values for the parameters in the function definition. In this example, object. The following function call assigns the value
45000 to the variable score:
fillOutScorecard("JEB", 45000);
42 Chapter 1: ActionScript Basics
scorecard is the instance name of an object; display and score are properties of the
"JEB" to the variable display and the value
The parameter initials in the function fillOutScorecard() is similar to a local variable; it exists while the function is called and ceases to exist when the function exits. If you omit parameters during a function call, the omitted parameters are passed as
undefined. If you provide
extra parameters in a function call that are not required by the function declaration, they are ignored.

Using variables in a function

Local variables are valuable tools for organizing code and making it easy to understand. When a function uses local variables, it can hide its variables from all other scripts in the SWF file; local variables are scoped to the body of the function and cease to exist when the function exits. Any parameters passed to a function are also treated as local variables.
You can also use global and regular variables in a function. However, if you modify global or regular variables, it is good practice to use script comments to document these modifications.

Returning values from a function

Use the function and replaces it with the value of the to use the
return statement to return values from functions. The return statement stops the
return statement. The following rules govern how
return statement in functions:
If you specify a return type other than Void for a function, you must include a return
statement followed by the returned value in the function.
If you specify a return type of Void, you generally do not need to include a return statement.
No matter what the return type, you can use a return statement to exit from the middle of a
function, provided the return statement is followed by a return value, according to the previous
rules.
If you don’t specify a return type, including a return statement is optional. If you don’t
include one, an empty string is returned.
For example, the following function returns the square of the parameter
x and specifies that the
returned value must be a Number:
function sqr(x:Number):Number {
return x * x; }
Some functions perform a series of tasks without returning a value. For example, the following function initializes a series of global variables:
function initialize() {
boat_x = _global.boat._x;
boat_y = _global.boat._y;
car_x = _global.car._x;
car_y = _global.car._y; }
Creating functions 43

Calling a user-defined function

To call a function, enter the target path to the name of the function, if necessary, and pass any required parameters inside parentheses. For example, the following statement invokes the function variable
var temp:Number = mathLib.sqr(3);
sqr() in the object mathLib, passes the parameter 3 to it, and stores the result in the
temp:
The following example uses an path to call the initialize() function that requires no parameters:
initialize();
44 Chapter 1: ActionScript Basics
CHAPTER 2

Creating Custom Classes with ActionScript 2.0

ActionScript 2.0 provides several powerful programming features found in other programming languages, such as Java. ActionScript 2.0 encourages program structures that are reusable, scalable, robust, and maintainable. It also decreases development time by providing users thorough coding assistance and debugging information. ActionScript 2.0 conforms more closely to the ECMA-262 Edition 3 standard (see www.ecma-international.org/publications/standards/
Ecma-262.htm).
The main features of ActionScript 2.0 include the following:
Familiar object-oriented programming (OOP) model The primary feature of
ActionScript 2.0 is a familiar model for creating object-oriented programs. ActionScript 2.0 implements several object-oriented concepts and keywords such as class, interface, and packages that will be familiar to you if you’ve programmed with Java.
Strict data typing ActionScript 2.0 also lets you explicitly specify data types for variables,
function parameters, and function return types. For example, the following code declares a variable named
var userName:String = "";
Compiler warnings and errors
enable the compiler to provide warnings and error messages that help you find bugs in your applications.
userName of type String (a built-in ActionScript data type, or class).
The previous two features (OOP model and strict data typing)

Principles of object-oriented programming

This section provides a brief introduction to principles involved in developing object-oriented programs. These principles are described in more depth in the rest of this chapter, along with details on how they are implemented in Macromedia Flex.
To learn about object-oriented programming principles, see the following topics:
“Objects” on page 46
“Classes and class members” on page 46
“Inheritance” on page 46
“Interfaces” on page 47
45
“Encapsulation” on page 47
“Polymorphism” on page 47

Objects

Think of a real-world object, such as a cat. A cat could be said to have properties (or states), such as name, age, and color; a cat also has behaviors such as sleeping, eating, and purring. In the world of object-oriented programming, objects also have properties and behaviors. Using object­oriented techniques, you can model a real-world object (such as a cat) or a more abstract object (such as a chemical process).
Note: The word “behaviors” is used generically here and does not refer to the Behaviors development panel in the Macromedia Flash interface.

Classes and class members

Continuing with the real-world analogy, consider that there are cats of different colors, ages, and names, with different ways of eating and purring. But despite their individual differences, all cats are members of the same category, or in object-oriented programming terms, the same class: the class of cats. In object-oriented programming terminology, each individual cat is said to be an instance of the cat class.
Likewise, in object-oriented programming, a class defines a blueprint for a type of object. The characteristics and behaviors that belong to a class are jointly referred to as members of that class. The characteristics (in the cat example; name, age, and color) are called properties of the class and are represented as variables; the behaviors (eating, sleeping) are called methods of the class and are represented as functions.
In ActionScript, you define a class with the
class statement (see “Creating and using classes”
on page 51).

Inheritance

One of the primary benefits of object-oriented programming is that you can create subclasses of a class; the subclass then inherits all the properties and methods of the superclass. The subclass typically defines additional methods and properties, or extends the superclass. Subclasses can also override (provide their own definitions for) methods inherited from a superclass.
For example, you might create a Mammal class that defines certain properties and behaviors common to all mammals. You could then create a Cat subclass that extends the Mammal class. Using subclasses lets you reuse code, so that instead of re-creating all the code common to both classes you can simply extend an existing class. Another subclass, say, the Siamese class, could extend the Cat class, and so on. In a complex application, determining how to structure the hierarchy of your classes is a large part of the design process.
In ActionScript, you use the
extends keyword to establish inheritance between a class and its
superclass. For more information, see “Creating subclasses” on page 55.
46 Chapter 2: Creating Custom Classes with ActionScript 2.0

Interfaces

Interfaces in object-oriented programming can be described as classes whose methods are not implemented (defined). Another class can implement the methods declared by the interface.
An interface can also be thought of as a “programming contract” that can be used to enforce relationships between otherwise unrelated classes. For example, suppose you are working with a team of programmers, each of whom is working on a different part (class) of the same application. While designing the application, you agree on a set of methods that the different classes will use to communicate. So you create an interface that declares these methods, their parameters, and their return types. Any class that implements this interface must provide definitions for those methods; otherwise, a compiler error will result.
You can also use interfaces to provide a limited form of multiple inheritance, which is not allowed in ActionScript 2.0. In multiple inheritance, a class extends more than one class. For example, in C++, the Cat class could extend the Mammal class as well as a Playful class, which has methods chaseTail and eatCatNip. As with Java, ActionScript 2.0 does not allow a class to extend multiple classes directly but does allow a class to extend a single class and implement multiple interfaces. So, you could create a Playful interface that declares the chaseTail and eatCatNip methods. A Cat class, or any other class, could then implement this interface and provide definitions for those methods.
Unlike Java interfaces, ActionScript interfaces exist at runtime, which allows type casting. For more information, see “Creating an interface” on page 58.

Encapsulation

In elegant object-oriented design, objects are seen as “black boxes” that contain, or encapsulate, functionality. A programmer should be able to interact with an object by knowing only its properties, methods, and events (its programming interface), without knowing the details of its implementation. This approach enables programmers to think at higher levels of abstraction and provides an organizing framework for building complex systems.
Encapsulation is why ActionScript 2.0 includes, for example, member access control, so details of the implementation can be made private and invisible to code outside an object. The code outside the object is forced to interact with the object’s programming interface rather than with the implementation details. This approach provides some important benefits; for example, it lets the creator of the object change the object’s implementation without requiring any changes to code outside of the object, as long as the programming interface doesn’t change.

Polymorphism

Object-oriented programming lets you express differences between individual classes using a technique called polymorphism, by which classes can override methods of their superclasses and define specialized implementations of those methods.
Principles of object-oriented programming 47
For example, you might start with a class called Mammal that has play() and sleep() methods. You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The subclasses override the of animals. Monkey implements the
play() method to pounce at a ball of yarn; Dog implements the play() method to fetch a ball.
Because the
play() method from the Mammal class, to reflect the habits of those particular kinds
play() method to swing from trees; Cat implements the
sleep() functionality is similar between the animals, you would use the superclass
implementation.

Using classes: a simple example

For those who are new to object-oriented programming, this section describes the workflow involved in creating and using classes in Flash and walks you through a simple hands-on example.
At a minimum, the workflow for creating classes involves the following steps:
1.
Defining a class in an ActionScript class file.
2.
Saving the class file to the directory that is in the ActionScript classpath (a location where Flex
looks for classes).
3.
Creating an instance of the class in another script, or creating a subclass based on the original
class.
This section also discusses a feature in ActionScript 2.0 called strict data typing, which lets you specify the data type for a variable, function parameter, or function return type.
Although this section discusses only classes, the general workflow is the same for using interfaces. For more information, see “Creating and using interfaces” on page 58.
For more information on using classes, see the following topics:
“Creating a class file” on page 48
“Creating an instance of the Person class” on page 50

Creating a class file

To create a class, you must first create an external ActionScript (AS) file. To create an external AS file, use your preferred code or text editor.
When you create a class file, you must decide where to store the file and tell Flex how it can find the file. To tell Flash how to find the file, you must make sure the directory in which you store the file is in the ActionScript classpath. For more information, see “Understanding the classpath”
on page 64.
To create the class file:
1.
Create a directory in your ActionScript classpath, and name it PersonFiles. This directory will
contain all the files for this project.
2.
Create a new file in your preferred text or code editor.
3.
Save the file as Person.as in the PersonFiles directory.
48 Chapter 2: Creating Custom Classes with ActionScript 2.0
4.
In your text editor, enter the following code (in this procedure, new code you type in each step
is
bold):
class Person {
}
This is called the class declaration. In its most basic form, a class declaration consists of the
class keyword, followed by the class name (Person, in this case), and then left and right curly
braces (
{}). Everything between the braces is called the class body and is where the class’s
properties and methods are defined.
The name of the class (Person) must exactly match the name of the AS file that contains it
(Person.as). This is very important; if these two names don’t match exactly, including
capitalization, the class won’t compile.
5.
To create the properties for the Person class, use the var keyword to define two variables named
age and name, as shown in the following example:
class Person {
var age:Number; var name:String;
}
Tip: By convention, class properties are defined at the top of the class body, which makes the
code easier to understand, but this isn’t required.
The colon syntax (var age:Number and var name:String) used in the variable declarations
is an example of strict data typing. When you type a variable in this way (
variableName:variableType
), the ActionScript 2.0 compiler ensures that any values
var
assigned to that variable match the specified type. If the correct data type is not used in the
FLA file importing this class, an error is thrown by the compiler. Using strict typing is good
practice and can make debugging your scripts easier. (For more information, see “Strict data
typing” on page 24.)
6.
Next, you’ll add a special function called a constructor function. In object-oriented
programming, the constructor function initializes each new instance of a class.
The constructor function always has the same name as the class. To create the class’s
constructor function, add the following code:
class Person {
var age:Number; var name:String;
// Constructor function function Person (myName:String, myAge:Number) {
this.name = myName; this.age = myAge;
}
}
Using classes: a simple example 49
The Person() constructor function takes two parameters, myName and myAge, and assigns
those parameters to the
name and age properties. The two function parameters are strictly
typed as String and Number, respectively. Unlike other functions, the constructor function
should not declare its return type. For more information about constructor functions, see
“Constructor functions” on page 52.
If you don’t create a constructor function, an empty one is created automatically
during compilation.
7.
Last, you’ll create the getInfo() method, which returns a preformatted string containing the
values of the
age and name properties. Add the getInfo() function definition to the class body,
after the constructor function, as shown in the following code:
class Person {
var age:Number; var name:String;
// Constructor function function Person (myName:String, myAge:Number) {
this.name = myName; this.age = myAge;
}
// Method to return property values function getInfo():String {
return("Hello, my name is " + this.name + " and I’m " + this.age + " years old."); }
}
This code is the completed code for this class. The return value of the getInfo() function is strictly typed (optional, but recommended) as a string.
8.
Save the file.
You’ve successfully created a class file. To continued with this example, see “Creating an instance
of the Person class” on page 50.

Creating an instance of the Person class

The next step is to create an instance of the Person class in another script and assign it to a variable. To create an instance of a custom class, you use the
new operator, the same as you would
when creating an instance of a built-in ActionScript class (such as the Date or Error class). You refer to the class using its fully qualified class name or import the class; see “Importing classes”
on page 65.
Continuing the example you started in “Creating a class file” on page 48, if you create a FLA file in the same directory as the class file you created, you can refer to the class file using the fully qualified class name, which is Person class and assigns it to the variable
var newPerson:Person = new Person("Nate", 32);
50 Chapter 2: Creating Custom Classes with ActionScript 2.0
Person. For example, the following code creates an instance of the
newPerson:
This code invokes the Person class’s constructor function, passing as parameters the values "Nate" and 32.
The
newPerson variable is typed as a Person object. Typing your objects in this way enables the
compiler to ensure that you don’t try to access properties or methods that aren’t defined in the class. See “Strict data typing” on page 24. (The exception is if you declare the class to be dynamic using the
To create an instance of the Person class:
1.
2.
3.
dynamic keyword. See “Creating dynamic classes” on page 56.)
Create a new file in your preferred text or code editor.
Save the file as createPerson.as in the PersonFiles directory you created.
Enter the following code:
var person_1:Person = new Person("Nate", 32); var person_2:Person = new Person("Jane", 28); trace(person_1.getInfo()); trace(person_2.getInfo());
This code creates two instances of the Person class, person_1 and person_2, and then calls the
getInfo() method on each instance.
You should now have a basic understanding of how to create and use classes in your scripts. The rest of this chapter discusses classes and interfaces in more detail.

Creating and using classes

As discussed in “Using classes: a simple example” on page 48, a class consists of two parts: the declaration and the body. The class declaration consists minimally of the followed by an identifier for the class name, then left and right curly braces ({}). Everything inside the braces is the class body, as shown in the following example:
class className {
// class body
}
You can define classes only in AS files. Class names must be identifiers—that is, the first character must be a letter, underscore (
_), or dollar sign ($), and each subsequent character must be a letter,
number, underscore, or dollar sign. The class name must exactly match the name of the AS file that contains it, including capitalization. In the following example, if you create a class called Shape, the AS file that contains the class definition must be named Shape.as:
// In file Shape.as class Shape {
// Shape class body
}
All AS class files that you create must be saved in one of the designated classpath directories— directories where Flash looks for class definitions when compiling scripts—that is, in the same directory where the FLA file that refers to the class is stored. For more information on including AS files in Flex applications, see “Using ActionScript” in Developing Flex Applications.
class statement,
Creating and using classes 51
If you are creating multiple custom classes, use packages to organize your class files. A package is a directory that contains one or more class files and resides in a designated classpath directory. Class names must be fully qualified within the file in which it is declared—that is, it must reflect the directory (package) in which it is stored.
For example, a class named myClasses.education.curriculum.RequiredClass is stored in the myClasses/education/curriculum package. The class declaration in the RequiredClass.as file looks like this:
class myClasses.education.curriculum.RequiredClass { }
For this reason, it’s good practice to plan your package structure before you begin creating classes. Otherwise, if you decide to move class files after you create them, you will have to modify the class declaration statements to reflect their new location. For more information on organizing classes, see “Using packages” on page 57.
For more information on creating and using classes, see the following topics:
“Constructor functions” on page 52
“Creating properties and methods” on page 53
“Controlling member access” on page 53
“Initializing properties inline” on page 54
“Creating subclasses” on page 55

Constructor functions

A class’s constructor is a special function that is called automatically when you create an instance of a class using the contains it. For example, the Person class you created contained the following constructor function:
// Person class constructor function function Person (myName:String, myAge:Number) {
this.name = myName; this.age = myAge;
}
If no constructor function is explicitly declared—that is, if you don’t create a function whose name matches that of the class—the compiler automatically creates an empty constructor function for you.
A class can contain only one constructor function; overloaded constructor functions are not allowed in ActionScript 2.0.
A constructor function should have no return type.
new operator. The constructor function has the same name as the class that
The
this keyword is not required in ActionScript 2.0 class definitions because the compiler
resolves the reference and adds it into the bytecode. However, using readability..
52 Chapter 2: Creating Custom Classes with ActionScript 2.0
this can improve your code’s

Creating properties and methods

A class’s members consist of properties (variable declarations) and methods (function definitions). You must declare and define all properties and methods inside the class body (the curly braces [{}]); otherwise, an error will occur during compilation.
Any variable declared within a class, but outside a function, is a property of the class. In the following example, the Person class discussed in “Using classes: a simple example” on page 48 has two properties,
class Person {
var age:Number; var name:String;
}
age and name, of type Number and String, respectively:
Similarly, any function declared within a class is considered a method of the class. In the Person class example, you created a single method called
class Person {
var age:Number; var name:String; function getInfo():String {
// getInfo() method definition
}
}
getInfo():
The this keyword is not required in ActionScript 2.0 class definitions because the compiler resolves the reference and adds it into the bytecode. However, using
this can improve your code’s
readability..

Controlling member access

By default, any property or method of a class can be accessed by any other class: all members of a class are public by default. However, in some cases you might want to protect data or methods of a class from access by other classes. You need to make those members private (available only to the class that declares or defines them).
You specify public or private members using the
public or private member attribute. For
example, the following code declares a private variable (a property) and a private method (a function). The following class (LoginClass) defines a private property named private method named
class LoginClass {
private var userName:String; private function getUserName():String {
return this.userName;
} // Constructor: function LoginClass(user:String) {
this.userName = user;
}
}
getUserName().
Creating and using classes 53
userName and a
Private members (properties and methods) are accessible only to the class that defines those members and to subclasses of that original class. Instances of the original class, or instances of subclasses of that class, cannot access privately declared properties and methods; that is, private members are accessible only within class definitions; not at the instance level.
For example, you could create a subclass of LoginClass called NewLoginClass. This subclass can access the private property (
class NewLoginClass extends LoginClass {
// can access userName and getUserName()
}
userName) and method (getUserName()) defined by LoginClass.
However, an instance of LoginClass or NewLoginClass cannot access those private members. For example, the following code would result in a compiler error indicating that
getUserName() is
private and can’t be accessed:
var loginObject:LoginClass = new LoginClass("Maxwell"); var user:String = loginObject.getUserName();
Member access control is a compile-time-only feature; at runtime, Flash Player does not distinguish between private or public members.
The
this keyword is not required in ActionScript 2.0 class definitions because the compiler
resolves the reference and adds it into the bytecode. However, using
this can improve your code’s
readability..

Initializing properties inline

You can initialize properties inline—that is, when you declare them—with default values, as shown in the following example:
class Person {
var age:Number = 50; var name:String = "John Doe";
}
When you initialize properties inline, the expression on the right side of an assignment must be a compile-time constant. That is, the expression cannot refer to anything that is set or defined at runtime. Compile-time constants include string literals, numbers, Boolean values,
undefined, as well as constructor functions for the following built-in classes: Array, Boolean,
null, and
Number, Object, and String.
For example, the following class definition initializes several properties inline:
class CompileTimeTest {
var foo:String = "my foo"; // OK var bar:Number = 5; // OK var bool:Boolean = true; // OK var name:String = new String("Jane"); // OK var who:String = foo; // OK, because 'foo' is a constant var whee:String = myFunc(); // error! not compile-time constant expression var lala:Number = whee; // error! not compile-time constant expression var star:Number = bar + 25; // OK, both 'bar' and '25' are constants
function myFunc():String {
54 Chapter 2: Creating Custom Classes with ActionScript 2.0
return "Hello world";
}
}
This rule applies only to instance variables (variables that are copied into each instance of a class), not class variables (variables that belong to the class). For more information about these kinds of variables, see “Instance and class members” on page 60.
When you initialize arrays inline, only one array is created for all instances of the class:
class Bar { var foo:Array = new Array(); }

Creating subclasses

In object-oriented programming, a subclass can inherit the properties and methods of another class, called the superclass. To create this kind of relationship between two classes, you use the
class statement’s extends clause. To specify a superclass, use the following syntax:
class SubClass extends SuperClass {}
The class you specify in SubClass inherits all the properties and methods defined by the superclass. For example, you might create a Mammal class that defines properties and methods common to all mammals. To create a variation of the Mammal class, such as a Marsupial class, you would extend the Mammal class—that is, create a subclass of the Mammal class.
class Marsupial extends Mammal {}
The subclass inherits all the properties and methods of the superclass, including any properties or methods that you have declared to be private using the
private keyword. (For more information
on private variables, see “Controlling member access” on page 53.)
You can extend your own custom classes as well as many of the built-in ActionScript classes. (You cannot extend the TextField class or static classes, such as the Math, Key, and Mouse classes.) When you extend a built-in ActionScript class, your custom class inherits all the methods and properties of the built-in class.
For example, the following code defines the class JukeBox, which extends the built-in Sound class. It defines an array called invokes the
class JukeBox extends Sound {
var songList:Array = new Array("beethoven.mp3", "bach.mp3", "mozart.mp3"); function playSong(songID:Number):Void {
}
}
loadSound() method, which it inherits from the Sound class.
this.loadSound(songList[songID]);
songList and a method called playSong() that plays a song and
If you don’t place a call to super() in the constructor function of a subclass, the compiler automatically generates a call to the constructor of its immediate superclass with no parameters as the first statement of the function. If the superclass doesn’t have a constructor, the compiler creates an empty constructor function and then generates a call to it from the subclass. However, if the superclass takes parameters in its definition, you must create a constructor in the subclass and call the superclass with the required parameters.
Creating and using classes 55
Multiple inheritance, or inheriting from more than one class, is not allowed in ActionScript 2.0. However, classes can effectively inherit from multiple classes if you use individual
extends
statements, as shown in the following example:
// not allowed class C extends A, B {} // allowed class B extends A {} class C extends B {}
You can also use interfaces to provide a limited form of multiple inheritance. See “Interfaces”
on page 47 and “Creating and using interfaces” on page 58.

Creating dynamic classes

By default, the properties and methods of a class are fixed. That is, an instance of a class can’t create or access properties or methods that weren’t originally declared or defined by the class. For example, consider a Person class that defines two properties,
class Person {
var name:String; var age:Number;
}
If, in another script, you create an instance of the Person class and try to access a property of the class that doesn’t exist, the compiler generates an error. For example, the following code creates a new instance of the Person class (
hairColor, which doesn’t exist:
var a_person:Person = new Person(); a_person.hairColor = "blue"; // compiler error
a_person) and then tries to assign a value to a property named
This code causes a compiler error because the Person class doesn’t declare a property named
hairColor. In most cases, this is exactly what you want to happen. Compiler errors may not seem
desirable, but they are very beneficial to programmers; good error messages help you to write correct code, by pointing out mistakes early in the coding process.
In some cases, however, you might want to add and access properties or methods of a class at runtime that aren’t defined in the original class definition. The just that. For example, the following code adds the
dynamic modifier to the Person class
discussed previously:
dynamic class Person2 {
var name:String; var age:Number;
}
Now, instances of the Person class can add and access properties and methods that aren’t defined in the original class, as shown in the following example:
var a_person:Person2 = new Person2(); a_person.hairColor = "blue";//no compiler error because class is dynamic trace(a_person.hairColor);
name and age:
dynamic class modifier lets you do
56 Chapter 2: Creating Custom Classes with ActionScript 2.0
Subclasses of dynamic classes are also dynamic, with one exception. Subclasses of the built-in MovieClip class are not dynamic by default, even though the MovieClip class itself is dynamic. This implementation provides you with more control over subclasses of the MovieClip class, because you can choose to make your subclasses dynamic or not:
class A extends MovieClip {} // A is not dynamic dynamic class B extends A {} // B is dynamic class C extends B {} // C is dynamic class D extends A {} // D is not dynamic dynamic class E extends MovieClip{} // E is dynamic
The following built-in classes are dynamic: Array, ContextMenu, ContextMenuItem, Function, LoadVars, LocalConnection, MovieClip, SharedObject and TextField.

Using packages

When you are creating classes, organize your ActionScript class files in packages. A package is a directory that contains one or more class files and that resides in a designated classpath directory (see the previous section, “Understanding the classpath”). A package can, in turn, contain other packages, called subpackages, each with its own class files.
Package names must be identifiers; that is, the first character must be a letter, underscore ( dollar sign (
Packages are commonly used to organize related classes. For example, you might have three related classes, Square, Circle, and Triangle, that are defined in Square.as, Circle.as, and Triangle.as. Assume that you’ve saved the AS files to a directory specified in the classpath, as shown in the following example:
// In Square.as: class Square {}
$), and each subsequent character must be a letter, number, underscore, or dollar sign.
_), or
// In Circle.as: class Circle {}
// In Triangle.as: class Triangle {}
Because these three class files are related, you might decide to put them in a package (directory) called Shapes. In this case, the fully qualified class name would contain the package path, as well as the simple class name. Package paths are denoted with dot (.) syntax, where each dot indicates a subdirectory.
For example, if you placed each AS file that defines a shape in the Shapes directory, you would need to change the name of each class file to reflect the new location, as follows:
// In Shapes/Square.as: class Shapes.Square {}
// In Shapes/Circle.as: class Shapes.Circle {}
// In Shapes/Triangle.as: class Shapes.Triangle {}
Using packages 57
To reference a class that resides in a package directory, you can either specify its fully qualified class name or import the package by using the
import statement (see the following section).

Creating and using interfaces

An interface in object-oriented programming is like a class whose methods have been declared, but otherwise don’t “do” anything. That is, an interface consists of “empty” methods.
One use of interfaces is to enforce a protocol between otherwise unrelated classes. For example, suppose you’re part of a team of programmers, each of whom is working on a different part—that is, a different class—of a large application. Most of these classes are unrelated, but you still need a way for the different classes to communicate. You need to define an interface, or communication protocol, to which all the classes must adhere.
One way to do this would be to create a class that defines all these methods, and then have each class extend, or inherit from, this superclass. But because the application consists of classes that are unrelated, it doesn’t make sense to put them all into a common class hierarchy. A better solution is to create an interface that declares the methods these classes will use to communicate, and then have each class implement (provide its own definitions for) those methods.
You can usually program successfully without using interfaces. When used appropriately, however, interfaces can make the design of your applications more elegant, scalable, and maintainable.
For more information on creating and using interfaces, see the following topics:
“Creating an interface” on page 58
“Interfaces as data types” on page 59

Creating an interface

The process for creating an interface is the same as for creating a class. As with classes, you can define interfaces only in external AS files. You declare an interface using the
interface keyword,
followed by the interface name, and then left and right curly braces ({}), which define the body of the interface, as shown in the following example:
interface interfaceName {
// interface method declarations
}
An interface can contain only method (function) declarations, including parameters, parameter types, and function return types.
For example, the following code declares an interface named MyInterface that contains two methods, specifies a return type of
method_2(), has a single parameter of type String, and specifies a return type of Boolean.
interface MyInterface {
}
58 Chapter 2: Creating Custom Classes with ActionScript 2.0
method_1() and method_2(). The first method, method_1(), has no parameters and
Void (meaning it does not return a value). The second method,
function method_1():Void; function method_2(param:String):Boolean;
Interfaces cannot contain any variable declarations or assignments. Functions declared in an interface cannot contain curly braces. For example, the following interface won’t compile:
interface BadInterface{
// Compiler error. Variable declarations not allowed in interfaces. var illegalVar;
// Compiler error. Function bodies not allowed in interfaces.
function illegalMethod(){ }
}
You can also use the extends keyword to create subclasses of an interface:
interface iA extends interface iB {}
The rules for naming interfaces and storing them in packages are the same as those for classes; see
“Creating and using classes” on page 51 and “Using packages” on page 57.

Interfaces as data types

Like a class, an interface defines a new data type. Any class that implements an interface can be considered to be of the type defined by the interface. This is useful for determining if a given object implements a given interface. For example, consider the following interface:
interface Movable {
function moveUp():Void; function moveDown():Void;
}
Now consider the class Box, which implements the Movable interface.
class Box implements Movable {
var xpos:Number; var ypos:Number; function moveUp():Void {
trace("moving up"); // method definition
} function moveDown():Void {
trace("moving down"); // method definition
}
}
In another script, such as the following code, where you create an instance of the Box class, you could declare a variable to be of the Movable type:
import Box; var newBox:Movable = new Box();
At runtime, you can cast an expression to an interface type. Unlike Java interfaces, ActionScript interfaces exist at runtime, which allows type casting. If the expression is an object that implements the interface or has a superclass that implements the interface, the object is returned. Otherwise,
null is returned. This is useful if you want to make sure that a particular object
implements a certain interface.
Creating and using interfaces 59
For example, the following code first checks if the object name newBox implements the Movable interface before calling the
if (Movable(newBox) != null) {
newBox.moveUp();
}
moveUp() method on the object:
For more information about casting, see “Casting objects” on page 25.

Instance and class members

In object-oriented programming, members (properties or methods) of a class can be instance members or class members. Instance members are created for each instance of the class; they are defined to the prototype of the class when they are declared outside of its constructor function. In contrast, class members are created once per class. (Class members are also known as static members.)
To invoke an instance method or access an instance property, you reference an instance of the class. In the following example,
showInfo() method:
picture_01.showInfo();
Class (static) members, however, are assigned to the class, not to any instance of the class. To invoke a class method or access a class property, you reference the class name, rather than a specific instance of the class, as shown in the following example:
ClassName.classMember;
For example, the ActionScript Math class consists only of static methods and properties. To call any of its methods, you don’t create an instance of the Math class. Instead, you simply call the methods on the Math class itself. The following code calls the
var square_root:Number = Math.sqrt(4);
picture_01, an instance of a custom class, invokes the
sqrt() method of the Math class:

Creating class members

All the members (methods and properties) discussed so far in this chapter are of a type called instance members. For each instance member, there’s a unique copy of that member in every instance of the class. For example, the
age member variable of the Person class is an instance
member, because each Person has a different age.
Another type of member is a class member. There is only one copy of a class member, which is used for the entire class.
The
age property would not be a good class member, because each person has a different age.
Only properties and methods that are shared by all individuals of the class should be class members.
Suppose that you want every class to have a
species member that indicates the proper Latin
name for the species that the class represents. For every Person object, the species is Homo sapiens. It would be wasteful to store a unique copy of the string
"Homo sapiens" for every
instance of the class, so this member should be a class member.
60 Chapter 2: Creating Custom Classes with ActionScript 2.0
Class members are declared with the static modifier. For example, you could declare the
species class member with the following code:
class Person {
static var species:String = "Homo sapiens"; ...
}
You can also declare methods of a class to be static, as shown in the following code:
static function functionName() {
// function body
}
Class (static) methods can access only class (static) properties, not instance properties. For example, the following code will result in a compiler error because the class method references the instance variable
class StaticTest {
var name:String="Ted";
static function getName():Void {
var local_name:String = name; // Error! Instance variables cannot be accessed in static functions.
}
}
name:
getName()
To solve this problem, you could either make the method an instance method or make the variable a class variable.
A common use of class members is the Singleton design pattern. The Singleton design pattern makes sure that a class has only one instance and provides a way of globally accessing the instance. For more information on the Singleton design pattern, see www.macromedia.com/devnet/mx/
coldfusion/articles/design_patterns.html.
Often there are situations when you need exactly one object of a particular type in a system. For example, in a chess game, there is only one chessboard, and in a country, there is only one capitol city. Even though there is only one object, it is attractive to encapsulate the functionality of this object in a class. However, you might need to manage and access the one instance of that object. Using a global variable is one way to do this, but global variables are often not desirable. A better approach is to make the class manage the single instance of the object itself using class members, such as the following example:
class Singleton {
private var instance:Singleton = null; public function doSomething():Void {
//...
} public static function getInstance():Singleton {
if (instance == null) {
instance = new Singleton(); } return instance;
}
}
Instance and class members 61
The Singleton object can then be accessed using Singleton.getInstance();
This also means that the Singleton object is not created until it is actually needed—that is, until some other code asks for it by calling the
getInstance method. This is typically called lazy
creation and can help code efficiency in many circumstances.

Using class members: a simple example

One use of class (static) members is to maintain state information about a class and its instances. For example, suppose you want to keep track of the number of instances that have been created from a particular class. An easy way to do this is to use a class property that’s incremented each time a new instance is created.
In the following example, you’ll create a class called Widget that defines a single, static instance counter named
widgetCount is incremented by 1 and the current value of widgetCount is displayed in the
widgetCount. Each time a new instance of the class is created, the value of
Output panel.
To create an instance counter using a class variable:
1.
Create a new ActionScript (AS) file.
2.
Add the following code to the file:
class Widget {
static var widgetCount:Number = 0; // initialize class variable function Widget() {
trace("Creating widget #" + widgetCount);
widgetCount++; }
}
The widgetCount variable is declared as static, so it initializes to 0 only once. Each time the Widget class’s constructor function is called, it adds 1 to
widgetCount and then shows the
number of the current instance that’s being created.
3.
Save your file as Widget.as.
4.
Add the following code to your script file:
// Before you create any instances of the class, // widgetCount is zero (0) trace("Widget count at start: " + Widget.widgetCount); var widget_1:Widget = new Widget(); var widget_2:Widget = new Widget(); var widget_3:Widget = new Widget();

Class members and subclasses

Class members propagate to subclasses of the superclass that defines those members. In the previous example (see “Using class members: a simple example” on page 62), you used a class property to keep track of the number of instances of the class you created. You could create a subclass of the Widget class, as shown in the following code:
class SubWidget extends Widget {
function SubWidget() {
62 Chapter 2: Creating Custom Classes with ActionScript 2.0
trace("Creating subwidget # "+Widget.widgetCount);
}
}
The ActionScript 2.0 compiler can resolve static member references within class definitions. In the previous example, if you don't specify the class name for the but instead refer only to is actually to
Widget.widgetCount and correctly exports that property. Similarly, if you referred
to the property as not in your AS file) as
widgetCount, the ActionScript 2.0 compiler ascertains that the reference
SubWidget.widgetCount, the compiler rewrites the reference (in the bytecode,
Widget.widgetCount because SubWidget is a subclass of the Widget class.
Widget.widgetCount property,
However, for optimal readability of your code, it is recommended that you always use explicit references in your code, as shown in the previous example, to easily identify where the definition of a static member resides.

Implicit getter/setter methods

Object-oriented programming practice discourages direct access to properties within a class. Classes typically define getter methods that provide read access and setter methods that provide write access to a given property. For example, imagine a class that contains a property called
userName:
var userName:String;
Instead of allowing instances of the class to directly access this property (obj.userName =
, for example), the class might have two methods, getUserName and setUserName, that
"Jody"
would be implemented as shown in the following example:
class LoginClass {
private var userName:String;
function LoginClass(name:String) {
this.userName = name;
} function getUserName():String {
return this.userName;
} function setUserName(name:String):Void {
this.userName = name;
}
}
As you can see, getUserName returns the current value of userName, and setUserName sets the value of then use the following syntax to get or set the
var obj:LoginClass = new LoginClass("RickyM"); // calling "get" method var name = obj.getUserName(); trace(name); // calling "set" method obj.setUserName("EnriqueI"); trace(obj.getUserName());
userName to the string parameter passed to the method. An instance of the class would
userName property:
Implicit getter/setter methods 63
However, if you want to use a more concise syntax, use implicit getter/setter methods. Implicit getter/setter methods let you access class properties in a direct manner, while maintaining good OOP practice.
To define these methods, use the set the value of a property, and add the keyword
get and set method attributes. You create methods that get or
get or set before the method name, as shown in
the following example:
class LoginClass2 {
private var userName:String;
function LoginClass2(name:String) {
this.userName = name;
} function get user():String {
return this.userName;
} function set user(name:String):Void {
this.userName = name;
}
}
A getter method must not take any parameters. A setter method must take exactly one required parameter. A setter method can have the same name as a getter method in the same scope. Getter/ setter methods cannot have the same name as other properties. For example, in the example code above that defines getter and setter methods named named
user in the same class.
user, you could not also have a property
Unlike ordinary methods, getter/setter methods are invoked without any parentheses or arguments. For example, the following syntax could now be used to access or modify the value of
userName with the getter/setter methods previously defined:
var obj:LoginClass2 = new LoginClass2("RickyM"); // calling "get" method trace(obj.user); // calling "set" method obj.user = "EnriqueI"; trace(obj.user);
Getter/setter method attributes cannot be used in interface method declarations.

Understanding the classpath

In order to use a class or interface that you’ve defined, Flash must locate the external AS files that contain the class or interface definition. The list of directories in which Flex searches for class and interface definitions is called the ActionScript classpath.
By default, the flex_root/WEB-INF/flex/user_classes directory is part of the ActionScript classpath. In addition, ActionScript classes can be in the same directory as the MXML file. For more information about including external ActionScript files in Flex applications, see “Using ActionScript” in Developing Flex Applications.
64 Chapter 2: Creating Custom Classes with ActionScript 2.0

Importing classes

To reference a class in another script, you must prefix the class name with the class’s package path. The combination of a class’s name and its package path is the class’s fully qualified class name. If a class resides in a top-level classpath directory—not in a subdirectory in the classpath directory— then its fully qualified class name is its class name.
To specify package paths, use dot (.) notation to separate package directory names. Package paths are hierarchical, where each dot represents a nested directory. For example, suppose you create a class named Data that resides in a com/xyzzycorporation/ package in your classpath. To create an instance of that class, you could specify the fully qualified class name, as shown in the following example:
var dataInstance = new com.xyzzycorporation.Data();
You can also use the fully qualified class name to type your variables, as shown in the following example:
var dataInstance:com.xyzzycorporation.Data = new Data();
You can use the import statement to import packages into a script, which lets you use a class’s abbreviated name rather than its fully qualified name. You can also use the wildcard character (*) to import all the classes in a package.
For example, suppose you created a class named UserClass that’s included in the package directory path com/xyzzycorporation/util/users:
// In the file com/xyzzycorporation/util/users/UserClass.as class com.xyzzycorporation.util.users.UserClass { ... }
Suppose that in another script, you imported that class using the import statement, as shown in the following example:
import com.xyzzycorporation.util.users.UserClass;
Later, in the same script, you could reference that class by its abbreviated name, as shown in the following example:
var myUser:UserClass = new UserClass();
You can use the wildcard character (*) to import all the classes in a given package. For example, suppose you have a package named ActionScript class files, Rosencrantz.as and Guildenstern.as. In another script, you could import both classes in that package using the wildcard character, as shown in the following code:
import com.xyzzycorporation.util.*;
The following example shows that you can then reference either of the classes directly in the same script:
var myRos:Rosencrantz = new Rosencrantz(); var myGuil:Guildenstern = new Guildenstern();
com.xyzzycorporation.util that contains two
Importing classes 65
66 Chapter 2: Creating Custom Classes with ActionScript 2.0
CHAPTER 3

Working with External Data

In Macromedia Flex, you can use ActionScript to load data from external sources into a SWF file. You can also send data from a SWF file for processing by an application server (such as Macromedia ColdFusion MX or Macromedia JRun) or another type of server-side script, such as PHP or Perl. Macromedia Flash Player can send and load data over HTTP or HTTPS or load from a local text file. You can also create persistent TCP/IP socket connections for applications that require low latency—for example, chat applications or stock quote services.
Data that you load into or send from a SWF file can be formatted as XML (Extensible Markup Language) or as name-value pairs.
Flash Player can also send data to and receive data from its host environment—a web browser, for example—or another instance of Flash Player on the same computer or web page.
By default, a SWF file can access only data that resides in exactly the same domain (for example, www.macromedia.com). For more information, see “Applying Flex Security” in Developing Flex Applications.

Sending and loading variables to and from a remote source

A SWF file is a window for capturing and displaying information, much like an HTML page. However, SWF files can stay loaded in the browser and continuously update with new information without having to reload the entire page. Using ActionScript functions and methods, you can send information to and receive information from server-side scripts, and receive information from text files and XML files.
In addition, server-side scripts can request specific information from a database and relay it to a SWF file. Server-side scripts can be written in different languages: some of the most common are CFML, Perl, ASP (Microsoft Active Server Pages), and PHP. By storing information in a database and retrieving it, you can create dynamic and personalized content for your SWF file. For example, you could create a message board, personal profiles for users, or a shopping cart that keeps track of a user’s purchases.
Several ActionScript functions and methods let you pass information into and out of a SWF file. Each function or method uses a protocol to transfer information and requires information to be formatted in a certain way.
67
The functions and MovieClip methods that use the HTTP or HTTPS protocol to send
information in URL-encoded format are
loadVariablesNum(), loadMovie(), and loadMovieNum().
getURL(), loadVariables(),
The LoadVars methods that use the HTTP or HTTPS protocol to send and load information
in URL-encoded format are
load(), send(), and sendAndLoad().
The methods that use HTTP or HTTPS protocol to send and load information as XML are
XML.send(), XML.load(), and XML.sendAndLoad().
The methods that create and use a TCP/IP socket connection to send and load information as
XML are
For more information, see the following topics:
XMLSocket.connect() and XMLSocket.send().
“Checking for loaded data” on page 68
“Using HTTP to connect to server-side scripts” on page 69
“Using the LoadVars class” on page 69
“About XML” on page 70
“Using the XML class” on page 71
“Using the XMLSocket class” on page 71

Checking for loaded data

Each function or method that loads data into a SWF file (except asynchronous: The results of the action are returned at an indeterminate time.
Before you can use loaded data in a SWF file, you must check to see if it has been loaded. For example, you can’t load variables and manipulate their values in the same script because the data to manipulate doesn’t exist in the file until it is loaded. In the following script, you cannot use the variable file
lastSiteVisited=www.macromedia.com
lastSiteVisited until you’re sure that the variable has loaded from the
myData.txt. In the file myData.txt, you would have text similar to the following example:
But if you used the following code, you could not trace the data that is loading:
loadVariables("myData.txt", 0); trace(lastSiteVisited);
If you use the XML.load(), XML.sendAndLoad(), and XMLSocket.connect() methods, you should define a handler that will process the data when it arrives. This handler is a property of an XML or XMLSocket object to which you assign a function you defined. The handlers are called automatically when the information is received. For the XML object, use
XML.onData(). For the XMLSocket object, use XMLSocket.onConnect().
For more information, see “Using the XML class” on page 71 and “Using the XMLSocket class”
on page 71. For information on how to load data in Flex applications, see also Developing Flex
Applications. For more information on using LoadVars to send and load data that can be processed after the data is received, see “Using the LoadVars class” on page 69.
XMLSocket.send()) is
XML.onLoad() or
68 Chapter 3: Working with External Data

Using HTTP to connect to server-side scripts

The
getURL() function and the MovieClip.loadVariables(), MovieClip.loadMovie(), and
MovieClip.getURL() methods can communicate with server-side scripts using HTTP or
HTTPS protocols. When used as a method of the MovieClip object,
getURL() sends all the
variables of the specified movie clip; each function (or method) handles its response as follows:
The getURL() function returns any information to a browser window, not to Flash Player.
The loadVariables() methods loads variables into Flash Player.
The loadMovie() methods loads a SWF file into a specified movie clip in Flash Player.
When you use several parameters:
loadVariables(), getURL(), or loadMovie(), you can specify
URL is the file in which the remote variables reside.
Location is the target in the SWF file that receives the variables. (The getURL() function does
not take this parameter.)
Variables sets the HTTP method, either GET (appends the variables to the end of the URL)
or
POST (sends the variables in a separate HTTP header), by which the variables are sent.
When this parameter is omitted, Flash Player defaults to
For example, if you want to track the high scores for a game, you could store the scores on a server and use
loadVariables() to load them into the SWF file each time someone played the game.
The function call might look like the following example:
loadVariables("http://www.mySite.com/scripts/high_score.cfm", scoreClip, GET);
This example loads variables from the ColdFusion script called high_score.cfm into the movie clip instance
Any variables loaded with the
scoreClip using the GET HTTP method.
loadVariables() function must be in the standard MIME format
application/x-www-form-urlencoded (a standard format used by CFM and CGI scripts). The file you specify in the
URL parameter of loadVariables() must write out the variable and value pairs
in this format so that Flash can read them.This file can specify any number of variables; variable and value pairs must be separated with an ampersand ( separated with a plus (
highScore1=54000&playerName1=RGoulet&highScore2=53455&playerName2=
WNewton&highScore3=42885&playerName3=TJones
Note: You might need to URL-encode certain characters, such as the plus (+) or ampersand (&) characters. For more information, see www.macromedia.com/support/flash/ts/documents/
url_encoding.htm.
+). For example, the following phrase defines several variables:
GET, but no variables are sent.
&), and words within a value must be
For more information, see getURL(), the LoadVars class entry, and “Using the LoadVars class”
on page 69.

Using the LoadVars class

If you are publishing to Flash Player 6 or later and want more flexibility than
loadVariables()
offers, you can use the LoadVars class instead to transfer variables between a SWF file and a server.
Sending and loading variables to and from a remote source 69
The LoadVars class was introduced in Flash Player 6 to provide a cleaner, more object-oriented interface for the common task of exchanging CGI data with a web server. Advantages of the LoadVars class include the following:
You don’t need to create container movie clips for holding data or clutter existing movie clips
with variables specific to client/server communication.
The class interface is similar to the XML object, which provides some consistency in
ActionScript. It uses the methods communication with a server. The main difference between the LoadVars and XML classes is that the LoadVars data is a property of the LoadVars object, rather than an XML Document Object Model (DOM) tree stored in the XML object.
load(), send(), and sendAndLoad() to initiate
The class interface is more straightforward—with methods named load, send,
sendAndLoad—than the older loadVariables interface.
You can get additional information about the communication, using the getBytesLoaded and
getBytesTotal methods
You can get progress information about the download of your data (although you can’t access
the data until it is fully downloaded).
The callback interface is through ActionScript methods (onLoad) instead of the obsolete,
deprecated
onClipEvent (data) approach required for loadVariables.
There are error notifications.
You can add custom HTTP request headers.
You must create a LoadVars object to call its methods. This object is a container to hold the loaded data.
For more information, see the LoadVars class entry.

About XML

Extensible Markup Language (XML) is becoming the standard for exchanging structured data in Internet applications. You can integrate data in Flash with servers that use XML technology to build sophisticated applications, such as chat or brokerage systems.
In XML, as with HTML, you use tags to specify, or mark up, a body of text. In HTML, you use predefined tags to indicate how text should appear in a web browser (for example, the indicates that text should be bold). In XML, you define tags that identify the type of a piece of data (for example, information from the way it appears, so the same XML document can be used and reused in different environments.
Every XML tag is called a node, or an element. Each node has a type (1, which indicates an XML element, or 3, which indicates a text node), and elements might also have attributes. A node nested in a node is called a child node. This hierarchical tree structure of nodes is called the XML DOM—much like the JavaScript DOM, which is the structure of elements in a web browser.
70 Chapter 3: Working with External Data
<password>VerySecret</password>). XML separates the structure of the
<b> tag
In the following example, <portfolio> is the parent node; it has no attributes and contains the child node
<portfolio>
<holding symbol="rich"
</portfolio>
<holding>, which has the attributes symbol, qty, price, and value:
qty="75" price="245.50" value="18412.50" />
For more information on XML, see www.w3.org/XML.

Using the XML class

The methods of the ActionScript XML class (for example,
insertBefore()) let you structure XML data in Flash to send to a server and manipulate and
appendChild(), removeNode(), and
interpret downloaded XML data.
The following XML class methods send and load XML data to a server by using the HTTP
POST method:
The load() method downloads XML from a URL and places it in an ActionScript
XML object.
The send()method encodes the XML object into an XML document and sends it to a
specified URL using the
POST method. If specified, a browser window displays returned data.
The sendAndLoad() method sends an XML object to a URL. Any returned information is
placed in an ActionScript XML object.
For more information, see the XML class entry and Developing Flex Applications.

Using the XMLSocket class

ActionScript provides a built-in XMLSocket class, which lets you open a continuous connection with a server. A socket connection lets the server publish, or push, information to the client as soon as that information is available. Without a continuous connection, the server must wait for an HTTP request. This open connection removes latency issues and is commonly used for real­time applications such as chats. The data is sent over the socket connection as one string and should be formatted as XML. You can use the XML class to structure the data.
To create a socket connection, you must create a server-side application to wait for the socket connection request and send a response to the SWF file. This type of server-side application can be written in a programming language such as Java.
Note: The XMLSocket class cannot tunnel through firewalls automatically because, unlike RTMP protocol, XMLSocket has no HTTP tunneling capability. If you need to use HTTP tunneling, consider using Flash Remoting or Flash Communication Server (which supports RTMP) instead.
You can use the connect() and send() methods of the XMLSocket class to transfer XML to and from a server over a socket connection. The with a web server port. The
send() method passes an XML object to the server specified in the
connect() method establishes a socket connection
socket connection.
Sending and loading variables to and from a remote source 71
When you invoke the connect() method, Flash Player opens a TCP/IP connection to the server and keeps that connection open until one of the following events happens:
The close() method of the XMLSocket class is called.
No more references to the XMLSocket object exist.
Flash Player exits.
The connection is broken (for example, the modem disconnects).
The following example creates an XML socket connection and sends data from the XML object
myXML. To understand the script, read the commented lines (indicated by the characters //):
//create XMLSocket object var theSocket:XMLSocket = new XMLSocket(); //connect to a site on unused port above 1024 using connect() method //enter localhost or 127.0.0.1 for local testing //for live server enter your domain www.yourdomain.com theSocket.connect("localhost", 12345); //displays text regarding connection theSocket.onConnect = function(myStatus) {
if (myStatus) {
conn_txt.text = "connection successful";
} else {
conn_txt.text = "no connection made";
} }; //data to send function sendData() {
var myXML:XML = new XML();
var mySend = myXML.createElement("thenode");
mySend.attributes.myData = "someData";
myXML.appendChild(mySend);
theSocket.send(myXML); } //button sends data sendButton.onRelease = function() {
sendData(); }; //traces data returned from socket connection theSocket.onData = function(msg:String):Void {
trace(msg); };
For more information, see the XMLSocket class entry and Developing Flex Applications.

Sending messages to and from Flash Player

To send messages from a SWF file to its host environment (for example, a web browser or the stand-alone Flash Player), you can use the your SWF file by using the capabilities of the host. For example, you could pass an function to a JavaScript function in an HTML page that opens a new browser window with specific properties.
72 Chapter 3: Working with External Data
fscommand() function. This function lets you extend
fscommand()
To control a SWF file in Flash Player from web browser scripting languages such as JavaScript, VBScript, and Microsoft JScript, you can use Flash Player methods—functions that send messages from a host environment to the SWF file. For more information, see Developing Flex Applications.
For more information, see the following topics:
“Using fscommand()” on page 73
“About using JavaScript to control Flash applications” on page 74

Using fscommand()

You use the Player, such as a web browser.
Note: Using fscommand to call Javascript does not work on the Safari or Internet Explorer browsers for the Macintosh.
The fscommand() function has two parameters: command and arguments. To send a message to the stand-alone version of Flash Player, you must use predefined commands and arguments. For example, the following event handler sets the stand-alone player to scale the SWF file to the full monitor screen size when the button is released:
my_btn.onRelease = function() {
fscommand("fullscreen", true); };
The following table shows the values you can specify for the command and arguments parameters of
fscommand() to control the playback and appearance of a SWF file playing in the stand-alone
player, including projectors. (A projector is a SWF file saved in a format that can run as a stand­alone application—that is, embedding Flash Player with your content in an executable file.)
fscommand() function to send a message to whichever program is hosting Flash
Command Arguments Purpose
quit
fullscreen
allowscale
showmenu
exec
To u s e
fscommand() to send a message to a scripting language such as JavaScript in a web
browser, you can pass any two parameters in the
None Closes the projector.
true
or false Specifying true sets Flash Player to full-screen mode.
Specifying
true
or false Specifying false sets the player so that the SWF file is always
drawn at its original size and never scaled. Specifying forces the SWF file to scale to 100% of the player.
true
or false Specifying true enables the full set of context menu items.
Specifying Settings and About Flash Player.
Path to application
Executes an application from within the projector.
false returns the player to normal menu view.
false dims all the context menu items except
command and arguments parameters. These
true
parameters can be strings or expressions and will be used in a JavaScript function that “catches,” or handles, the
fscommand() function.
Sending messages to and from Flash Player 73
An fscommand() function invokes the JavaScript function moviename_DoFSCommand in the HTML page that embeds the SWF file, where by the
name attribute of the embed tag or the id attribute of the object tag. If Flash Player is
assigned the name
myMovie, the JavaScript function invoked is myMovie_DoFSCommand.
In Visual Basic, Visual C++, and other programs that can host ActiveX controls,
moviename is the name of Flash Player as assigned
fscommand()
sends a VB event with two strings that can be handled in the environment’s programming language. For more information, use the keywords Flash method to search the Flash Support Center at www.macromedia.com/support/flash.

About using JavaScript to control Flash applications

Flash Player 6 (6.0.40.0) and later supports certain JavaScript methods that are specific to Flash applications, as well as these JavaScript methods and
FSCommand, in Netscape 6.2 and later. Earlier versions do not support
FSCommand in Netscape 6.2 or later. For more information, see the
Macromedia Support Center article, “Scripting With Flash” at www.macromedia.com/support/
flash/publishexport/scriptingwithflash/.
74 Chapter 3: Working with External Data
PART II

Reference

This part provides syntax and usage information for every element in the ActionScript language. It also contains appendixes that provide reference material you may want to review as you write your scripts. For an overview of how to use ActionScript, see “Part I, “Welcome to ActionScript.”
Chapter 4: About the ActionScript Language Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Chapter 5: ActionScript Core Language Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Chapter 6: ActionScript Core Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Chapter 7: ActionScript for Flash. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
Appendix A: Deprecated Flash 4 operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
Appendix B: Keyboard Keys and Key Code Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
PART II
CHAPTER 4

About the ActionScript Language Reference

The next three chapters of this manual describe the syntax and use of ActionScript elements in Macromedia Flex. The chapters list all ActionScript elements that are common to Macromedia Flash and to Flex—operators, keywords, statements, actions, properties, functions, classes, and methods.
The information in these chapters is organized as follows:
Chapter 5, “ActionScript Core Language Elements,” on page 80 explains all of the elements of
the ActionScript language that are not related to a particular class or to a particular
Macromedia product.
Chapter 6, “ActionScript Core Classes,” on page 232 documents all of the classes of the
ActionScript language that are not related to a particular Macromedia product.
Chapter 7, “ActionScript for Flash,” on page 490 describes functions, properties, and classes of
Macromedia Flash Player that you can use in a Macromedia Flex application, if appropriate.
For additional elements that are available for Flex, see Flex ActionScript and MXML API Reference.
Use the information in the sample entries to interpret the structure and conventions used in these types of entries. To use examples in a script, copy the example code from this manual and paste it into a script file.

Sample entry for most ActionScript elements

The following sample entry explains the conventions used for all ActionScript elements that are not classes.
Entry title
Entries are listed alphabetically within a chapter. The alphabetization ignores capitalization, leading underscores, and so on.
Availability
Unless otherwise noted, the Availability section tells which versions of Flash Player support the element. This information is not relevant to Flex; the Flex player supports all elements of the ActionScript language.
77
Usage
This section provides correct syntax for using the ActionScript element in your code. The required portion of the syntax is in
code font
Parameters
. Brackets ([]) indicate optional parameters.
code font, and the code that you provide is in italicized
This section describes any parameters listed in the syntax.
Returns
This section identifies what, if any, values the element returns.
Description
This section identifies the type of element (for example, operator, method, function, and so on) and then describes how to use the element.
Example
This section provides a code sample demonstrating how to use the element.
See also
This section lists related ActionScript dictionary entries.

Sample entry for classes

The following sample dictionary entry explains the conventions used for built-in ActionScript classes. Core ActionScript classes are listed in Chapter 5, “ActionScript Core Language Elements,”
on page 80. Classes that are specific to Flash are listed alphabetically with other Flash language
elements in Chapter 7, “ActionScript for Flash,” on page 490. Flex supports the Flash elements; however, they might not be appropriate in all Flex applications. For more information, see the description for each element.
Entry title
The entry title provides the name of the class. The class name is followed by general descriptive information.
Method and property summary tables
Each class entry contains a table listing all of the associated methods. If the class has properties (often constants), event handlers, or event listeners, these elements are summarized in additional tables. All of the elements listed in these tables also have their own entries, which follow the class entry.
Constructor
If a class requires that you use a constructor to access its methods and properties, the constructor is described in each class entry. This description has all of the standard elements (usage, description, and so on) of other entries.
78 Chapter 4: About the ActionScript Language Reference
Method, property, and event handler listings
The methods, properties, and event handlers of a class are listed alphabetically after the class entry.
Sample entry for classes 79
CHAPTER 5

ActionScript Core Language Elements

This chapter documents all the elements of the ActionScript language that are not related to a particular class or to a particular Macromedia product. That is, all products that support ActionScript have access to any language element in this chapter. For information on the classes that all Macromedia products support, see Chapter 6, “ActionScript Core Classes,” on page 232.
For information on additional language elements and classes that Flex supports, see Developing Flex Applications.
80
CHAPTER 5
ActionScript Core Language Elements
–– (decrement)
Availability
Flash Player 4.
Usage
––expression
expression––
Parameters
expression
Returns
A number.
Description
Operator (arithmetic); a pre-decrement and post-decrement unary operator that subtracts 1 from the
expression. The expression can be a variable, element in an array, or property of an object.
The pre-decrement form of the operator ( returns the result. The post-decrement form of the operator (
expression and returns the initial value of expression (the value prior to the subtraction). For
more information, see “Operator precedence and associativity” on page 32.
A number or a variable that evaluates to a number.
––expression) subtracts 1 from expression and
expression––) subtracts 1 from the
Example
The pre-decrement form of the operator decrements x to 2 (x - 1 = 2) and returns the result as y:
var x:Number = 3; var y:Number = --x; //y is equal to 2
The post-decrement form of the operator decrements x to 2 (x - 1 = 2) and returns the original value of
var x:Number = 3; var y:Number = x--; //y is equal to 3
x as the result y:
The following example loops from 10 to 1, and each iteration of the loop decreases the counter variable
for (var i = 10; i>0; i--) {
}
i by 1.
trace(i);
–– (decrement) 81

++ (increment)

Availability
Flash Player 4.
Usage
++expression
expression++
Parameters
expression
Returns
A number.
Description
Operator (arithmetic); a pre-increment and post-increment unary operator that adds 1 to
expression. The expression can be a variable, element in an array, or property of an object.
The pre-increment form of the operator ( result. The post-increment form of the operator ( returns the initial value of
The pre-increment form of the operator increments as
y:
var x:Number = 1; var y:Number = ++x; trace("x:"+x);//traces x:2 trace("y:"+y);//traces y:2
The post-increment form of the operator increments x to 2 (x + 1 = 2) and returns the original value of
var x:Number = 1; var y:Number = x++; trace("x:"+x);//traces x:2 trace("y:"+y);//traces y:1
For more information, see “Operator precedence and associativity” on page 32.
A number or a variable that evaluates to a number.
++expression) adds 1 to expression and returns the
expression++) adds 1 to expression and
expression (the value prior to the addition).
x to 2 (x + 1 = 2) and returns the result
x as the result y:
Example
The following example uses ++ as a post-increment operator to make a while loop run five times:
var i:Number = 0; while (i++<5) {
trace("this is execution "+i); } /* output:
this is execution 1
this is execution 2
this is execution 3
this is execution 4
82 Chapter 5: ActionScript Core Language Elements
this is execution 5 */
The following example uses ++ as a pre-increment operator:
var a:Array = []; // var a:Array = new Array(); var i:Number = 0; while (i<10) {
a.push(++i); } trace(a.toString());//traces: 1,2,3,4,5,6,7,8,9,10
This example also uses ++ as a pre-increment operator.
var a:Array = []; for (var i = 1; i<=10; ++i) {
a.push(i); } trace(a.toString());//traces: 1,2,3,4,5,6,7,8,9,10
This script writes the following result to the log file:
1,2,3,4,5,6,7,8,9,10
The following example uses ++ as a post-increment operator in a while loop:
// using a while loop var a:Array = []; // var a:Array = new Array(); var i:Number = 0; while (i<10) {
a.push(i++); } trace(a.toString());//traces 0,1,2,3,4,5,6,7,8,9
The following example uses ++ as a post-increment operator in a for loop:
// using a for loop var a:Array = []; // var a:Array = new Array(); for (var i = 0; i<10; i++) {
a.push(i); } trace(a.toString());//traces 0,1,2,3,4,5,6,7,8,9
This script writes the following result to the log file:
0,1,2,3,4,5,6,7,8,9

! (logical NOT)

Availability
Flash Player 4.
Usage
!expression
! (logical NOT) 83
Parameters
expression
Returns
An expression or a variable that evaluates to a Boolean value.
A Boolean value.
Description
Operator (logical); inverts the Boolean value of a variable or expression. If expression is a variable with the absolute or converted value expression
x && y evaluates to false, the expression !(x && y) evaluates to true.
true, the value of !expression is false. If the
The following expressions illustrate the result of using the logical NOT (!) operator:
!true returns false
!false
returns true
For more information, see “Operator precedence and associativity” on page 32.
Example
In the following example, the variable happy is set to false. The if condition evaluates the condition
!happy, and if the condition is true, the trace() statement sends a string to the log
file.
var happy:Boolean = false; if (!happy) {
trace("don’t worry, be happy");//traces don’t worry, be happy }
The statement traces because !false equals true.
See also
!= (inequality) (equality)
, !== (strict inequality), && (logical AND), || (logical OR), ==
, === (strict equality)

!= (inequality)

Availability
Flash Player 5.
Usage
expression1 != expression2
Parameters
None.
Returns
A Boolean value.
84 Chapter 5: ActionScript Core Language Elements
Description
Operator (inequality); tests for the exact opposite of the equality (==) operator. If expression1 is equal to
expression2, the result is false. As with the equality (==) operator, the definition of
equal depends on the data types being compared, as illustrated in the following list:
Numbers, strings, and Boolean values are compared by value.
Objects, arrays, and functions are compared by reference.
A variable is compared by value or by reference, depending on its type.
Comparison by value means what most people would expect equals to mean—that two expressions have the same value. For example, the expression (2 + 3) is equal to the expression (1 + 4) when compared by value.
Comparison by reference means that two expressions are equal only if they both refer to the same object, array, or function. Values inside the object, array, or function are not compared.
When comparing by value, if ActionScript will attempt to convert the data type of
expression1. For more information, see “Automatic data typing” on page 24 and “Operator
precedence and associativity” on page 32.
Example
The following example illustrates the result of the inequality (!=) operator:
trace(5 != 8);// returns true trace(5 != 5) //returns false
The following example illustrates the use of the inequality (!=) operator in an if statement:
var a:String = "David"; var b:String = "Fool"; if (a != b) {
trace("David is not a fool"); }
The following example illustrates comparison by reference with two functions:
var a:Function = function() { trace("foo"); }; var b:Function = function() { trace("foo"); }; a(); // foo b(); // foo trace(a!=b); // true a = b; a(); // foo b(); // foo trace(a!=b); // false
expression1 and expression2 are different data types,
expression2 to match that of
// trace statement output: foo foo
!= (inequality) 85
true foo foo false
The following example illustrates comparison by reference with two arrays:
var a:Array = [ 1, 2, 3 ]; var b:Array = [ 1, 2, 3 ]; trace(a); // 1, 2, 3 trace(b); // 1, 2, 3 trace(a!=b); // true a = b; trace(a); // 1, 2, 3 trace(b); // 1, 2, 3 trace(a!=b); // false
// trace statement output: 1,2,3 1,2,3 true 1,2,3 1,2,3 false
See also
! (logical NOT) (equality)
, !== (strict inequality), && (logical AND), || (logical OR), ==
, === (strict equality)

!== (strict inequality)

Availability
Flash Player 6.
Usage
expression1 !== expression2
Parameters
None.
Returns
A Boolean value.
86 Chapter 5: ActionScript Core Language Elements
Description
Operator; tests for the exact opposite of the strict equality (===) operator. The strict inequality operator performs the same as the inequality operator except that data types are not converted. For more information, see “Automatic data typing” on page 24. If
expression2, and their data types are equal, the result is false. As with the strict equality (===)
expression1 is equal to
operator, the definition of equal depends on the data types being compared, as illustrated in the following list:
Numbers, strings, and Boolean values are compared by value.
Objects, arrays, and functions are compared by reference.
A variable is compared by value or by reference, depending on its type.
For more information, see “Operator precedence and associativity” on page 32.
Example
The comments in the following code show the returned value of operations that use the equality (
==), strict equality (===), and strict inequality (!==) operators:
var s1:String = "5"; var s2:String = "5"; var s3:String = "Hello"; var n:Number = 5; var b:Boolean = true;
trace(s1 == s2); // true trace(s1 == s3); // false trace(s1 == n); // true trace(s1 == b); // false
trace(s1 === s2); // true trace(s1 === s3); // false trace(s1 === n); // false trace(s1 === b); // false
trace(s1 !== s2); // false trace(s1 !== s3); // true trace(s1 !== n); // true trace(s1 !== b); // true
See also
! (logical NOT) === (strict equality)
, != (inequality), && (logical AND), || (logical OR), == (equality),

% (modulo)

Availability
Flash Player 4.
Usage
expression1 % expression2
% (modulo) 87
Parameters
None.
Returns
A number.
Description
Operator (arithmetic); calculates the remainder of expression1 divided by expression2. If either of the convert them to numbers. The
expression parameters are non-numeric, the modulo (%) operator attempts to
expression can be a number or string that converts to a numeric
value. For more information, see “Automatic data typing” on page 24 and “Operator precedence
and associativity” on page 32.
Example
The following numeric example uses the modulo (%) operator:
trace(12%5); // traces 2 trace(4.3%2.1); // traces 0.0999999999999996 trace(4%4); // traces 0
The first trace returns 2, rather than 12/5 or 2.4, because the modulo (%) operator returns only the remainder. The second trace returns 0.0999999999999996 instead of the expected 0.1 because of the limitations of floating-point accuracy in binary computing.
See Also
/ (division)
.

%= (modulo assignment)

Availability
Flash Player 4.
Usage
expression1 %= expression2
Parameters
None.
Returns
A number.
Description
Operator (arithmetic compound assignment); assigns expression1 the value of expression1 %
expression2
x %= y x = x % y
For more information, see “Operator precedence and associativity” on page 32.
88 Chapter 5: ActionScript Core Language Elements
. The following two expressions are equivalent:
Example
The following example assigns the value 4 to the variable x:
var x:Number = 14; var y:Number = 5; trace(x%=y); // output: 4
See also
% (modulo)

& (bitwise AND)

Availability
Flash Player 5.
Usage
expression1 & expression2
Parameters
None.
Returns
A 32-bit integer.
Description
Operator (bitwise); converts expression1 and expression2 to 32-bit unsigned integers, and performs a Boolean AND operation on each bit of the integer parameters. Floating-point numbers are converted to integers by discarding any digits after the decimal point. The result is a new 32-bit integer.
Positive integers are converted to an unsigned hex value with a maximum value of 4294967295 or 0xFFFFFFFF; values larger than the maximum have their most significant digits discarded when they are converted so the value is still 32-bit. Negative numbers are converted to an unsigned hex value using the two’s complement notation, with the minimum being -2147483648 or 0x800000000; numbers less than the minimum are converted to two’s complement with greater precision and then have the most significant digits discarded as well.
The return value is interpreted as a two’s complement number with sign, so the return is an integer in the range -2147483648 to 2147483647.
For more information, see “Operator precedence and associativity” on page 32.
Example
The following example compares the bit representation of the numbers and returns 1 only if both bits at the same position are 1. In this ActionScript, you add 13 (binary 1101) and 11 (binary
1011) and return 1 only in the position where both numbers have a 1.
var insert:Number = 13; var update:Number = 11; trace(insert & update);// output : 9 (or 1001 binary)
& (bitwise AND) 89
In the numbers 13 and 11 the result is 9 because only the first and last positions in both numbers have the number 1.
The following examples show the behavior of the return value conversion:
trace(0xFFFFFFFF); // 4294967295 trace(0xFFFFFFFF & 0xFFFFFFFF); // -1 trace(0xFFFFFFFF & -1); // -1 trace(4294967295 & -1); // -1 trace(4294967295 & 4294967295); // -1
See Also
&= (bitwise AND assignment) (bitwise OR)
, |= (bitwise OR assignment), ~ (bitwise NOT)
, ^ (bitwise XOR), ^= (bitwise XOR assignment), |

&& (logical AND)

Availability
Flash Player 4.
Usage
expression1 && expression2
Parameters
None.
Returns
A Boolean value.
Description
Operator (logical); performs a Boolean operation on the values of one or both of the expressions. Evaluates expression evaluates to on the right side of the operator) is evaluated. If
true; otherwise, it is false.
Expression Evaluates
true&&true
true&&false
false&&false
false&&true
expression1 (the expression on the left side of the operator) and returns false if the
false. If expression1 evaluates to true, expression2 (the expression
expression2 evaluates to true, the final result is
true
false
false
false
For more information, see “Operator precedence and associativity” on page 32.
90 Chapter 5: ActionScript Core Language Elements
Example
The following example uses the logical AND (&&) operator to perform a test to determine if a player has won the game. The
turns variable and the score variable are updated when a player
takes a turn or scores points during the game. The script writes “You Win the Game!” to the log file when the player’s score reaches 75 or higher in 3 turns or less.
var turns:Number = 2; var score:Number = 77; if ((turns<=3) && (score>=75)) {
trace("You Win the Game!"); } else {
trace("Try Again!"); } /* output:
You Win the Game! */
See also
! (logical NOT) (equality)
, != (inequality), !== (strict inequality), || (logical OR), ==
, === (strict equality)

&= (bitwise AND assignment)

Availability
Flash Player 5.
Usage
expression1 &= expression2
Parameters
None.
Returns
A 32-bit integer; the value of expression1 & expression2.
Description
Operator; assigns expression1 the value of expression1 & expression2. For example, the following two expressions are equivalent:
x &= y; x = x & y;
For more information, see “Operator precedence and associativity” on page 32.
Example
The following example assigns the value 9 to x:
var x:Number = 15; var y:Number = 9; trace(x &= y); // output: 9
&= (bitwise AND assignment) 91
See also
& (bitwise AND) (bitwise OR assignment)
, ^ (bitwise XOR), ^= (bitwise XOR assignment), | (bitwise OR), |=
, ~ (bitwise NOT)

() (parentheses)

Availability
Flash Player 4.
Usage
(expression1 [, expression2])
(expression1, expression2)
function(parameter1,..., parameterN)
Parameters
expression1, expression2
function The function to be performed on the contents of the parentheses.
parameter1...parameterN A series of parameters to execute before the results are passed as
parameters to the function outside the parentheses.
Returns
Nothing.
Description
Operator; performs a grouping operation on one or more parameters, performs sequential evaluation of expressions, or surrounds one or more parameters and passes them as parameters to a function outside the parentheses.
Numbers, strings, variables, or text.
Usage 1: Controls the order in which the operators execute in the expression. Parentheses override the normal precedence order and cause the expressions within the parentheses to be evaluated first. When parentheses are nested, the contents of the innermost parentheses are evaluated before the contents of the outer ones.
Usage 2: Evaluates a series of expressions, separated by commas, in sequence, and returns the result of the final expression.
Usage 3: Surrounds one or more parameters and passes them as parameters to the function outside the parentheses.
For more information, see “Operator precedence and associativity” on page 32.
Example
Usage 1: The following statements show the use of parentheses to control the order in which expressions are executed (the value of each expression is written to the log file):
trace((2+3)*(4+5));//writes 45 trace(2+(3*(4+5)));//// writes 29 trace(2+(3*4)+5);// writes 19
92 Chapter 5: ActionScript Core Language Elements
Usage 2: The following example evaluates the function foo(), and then the function bar(), and returns the result of the expression
var a:Number = 1; var b:Number = 2; function foo() {
a += b; } function bar() {
b *= 10; } trace((foo(), bar(), a+b)); // outputs 23
a + b:
Usage 3: The following example shows the use of parentheses with functions:
var today:Date = new Date(); trace(today.getFullYear()); // traces current year function traceParameter(param):Void {
trace(param); } traceParameter(2*2);//traces 4
See also
with
– (minus)
Availability
Flash Player 4.
Usage
(Negation) -expression
(Subtraction) expression1 - expression2
Parameters
None.
Returns
An integer or floating-point number.
Description
Operator (arithmetic); used for negating or subtracting.
Usage 1: When used for negating, it reverses the sign of the numerical
expression.
Usage 2: When used for subtracting, it performs an arithmetic subtraction on two numerical expressions, subtracting
expression2 from expression1. When both expressions are integers,
the difference is an integer. When either or both expressions are floating-point numbers, the difference is a floating-point number.
For more information, see “Operator precedence and associativity” on page 32.
– (minus) 93
Example
Usage 1: The following statement reverses the sign of the expression 2 + 3:
trace(-(2+3));// output: -5
Usage 2: The following statement subtracts the integer 2 from the integer 5:
trace(5-2);// output: 3
The result, 3, is an integer.
Usage 3: The following statement subtracts the floating-point number 1.5 from the floating-point number 3.25:
trace(3.25-1.5);// output: 1.75
The result, 1.75, is a floating-point number.

* (multiplication)

Availability
Flash Player 4.
Usage
expression1 * expression2
Parameters
None.
Returns
An integer or floating-point number.
Description
Operator (arithmetic); multiplies two numerical expressions. If both expressions are integers, the product is an integer. If either or both expressions are floating-point numbers, the product is a floating-point number.
For more information, see “Operator precedence and associativity” on page 32.
Example
Usage 1: The following statement multiplies the integers 2 and 3:
trace(2*3); // output: 6
The result, 6, is an integer.
Usage 2: This statement multiplies the floating-point numbers 2.0 and 3.1416:
trace(2.0 * 3.1416); // output: 6.2832
The result, 6.2832, is a floating-point number.
94 Chapter 5: ActionScript Core Language Elements

*= (multiplication assignment)

Availability
Flash Player 4.
Usage
expression1 *= expression2
Parameters
None.
Returns
The value of expression1 * expression2. If an expression cannot be converted to a numeric value, it returns
Description
Operator (arithmetic compound assignment); assigns expression1 the value of expression1 *
expression2. For example, the following two expressions are equivalent:
x *= y x = x * y
For more information, see “Operator precedence and associativity” on page 32.
Example
Usage 1: The following example assigns the value 50 to the variable x:
var x:Number = 5; var y:Number = 10; trace(x *= y); // output: 50
Usage 2: The second and third lines of the following example calculate the expressions on the right side of the equal sign and assign the results to
var i:Number = 5; var x:Number = 4-6; var y:Number = i+2; trace(x *= y); // output: -14
NaN (not a number).
x and y:
See also
* (multiplication)

, (comma)

Availability
Flash Player 4.
Usage
(expression1, expression2 [, expressionN...])
, (comma) 95
Parameters
None.
Returns
The value of expression1, expression2, and so on.
Description
Operator; evaluates expression1, then expression2, and so on. This operator is primarily used with the
for loop statement and is often used with the parentheses () operator.
For more information, see “Operator precedence and associativity” on page 32.
Example
The following example uses the comma (,) operator in a for loop:
for (i = 0, j = 0; i < 3 && j < 3; i++, j+=2) {
trace("i = " + i + ", j = " + j); } // Output: // i = 0, j = 0 // i = 1, j = 2
The following example uses the comma (,) operator without the parentheses () operator and illustrates that the comma operator returns only the value of the first expression without the parentheses () operator:
var v:Number = 0; v = 4, 5, 6; trace(v); // output: 4
The following example uses the comma (,) operator with the parentheses () operator and illustrates that the comma operator returns the value of the last expression when used with the parentheses () operator:
var v:Number = 0; v = (4, 5, 6); trace(v); // output: 6
The following example uses the comma (,) operator without the parentheses () operator and illustrates that the comma operator sequentially evaluates all of the expressions but returns the value of the first expression. The second expression,
z++, is evaluated and z is incremented by
one.
var v:Number = 0; var z:Number = 0; v = v + 4 , z++, v + 6; trace(v); // output: 4 trace(z); // output: 1
The following example is identical to the previous example except for the addition of the parentheses () operator and illustrates once again that, when used with the parentheses () operator, the comma (,) operator returns the value of the last expression in the series:
var v:Number = 0;
96 Chapter 5: ActionScript Core Language Elements
var z:Number = 0; v = (v + 4, z++, v + 6); trace(v); // output: 6 trace(z); // output: 1
See also
() (parentheses)

. (dot)

Availability
Flash Player 4.
Usage
object.property_or_method
instancename.childinstance
Parameters
object
An instance of a class. The object can be an instance of any of the built-in ActionScript
classes or a custom class. This parameter is always to the left of the dot (.) operator.
property_or_method The name of a property or method associated with an object. All the
valid methods and properties for the built-in classes are listed in the method and property summary tables for that class. This parameter is always to the right of the dot (.) operator.
instancename The instance name of a movie clip.
childinstance A movie clip instance that is a child of, or nested in, another movie clip.
Returns
The method, property or movie clip named on the right side of the dot.
Description
Operator; used to navigate movie clip hierarchies to access nested (child) movie clips, variables, or properties. The dot operator is also used to test or set the properties of an object or top-level class, execute a method of an object or top-level class, or create a data structure.
For more information, see “Operator precedence and associativity” on page 32.
Example
The following example identifies the current value of the variable hairColor in the movie clip
person_mc:
person_mc.hairColor
The following example creates a new movie clip within the _root scope. Then a text field is created inside the movie clip called
true and then populated with the current date.
this.createEmptyMovieClip("container_mc", this.getNextHighestDepth());
container_mc. The text field’s autoSize property is set to
. (dot) 97
this.container_mc.createTextField("date_txt", this.getNextHighestDepth(), 0,
0, 100, 22); this.container_mc.date_txt.autoSize = true; this.container_mc.date_txt.text = new Date();
The dot (.) operator is used when targeting instances within the SWF file and when you need to set properties and values for those instances.

: (type)

Availability
Flash Player 6.
Usage
[modifiers] var variableName:type
function functionName():type { ... }
function functionName(parameter1:type, ... , parameterN:type) [ :type ]{ ... }
Parameters
variableName
type A native data type, class name that you have defined, or interface name.
functionName An identifier for a function.
parameter An identifier for a function parameter.
Description
Operator; used for strict data typing; this operator specifies the variable type, function return type, or function parameter type. When used in a variable declaration or assignment, this operator specifies the variable’s type; when used in a function declaration or definition, this operator specifies the function’s return type; when used with a function parameter in a function definition, this operator specifies the variable type expected for that parameter.
An identifier for a variable.
Types are a compile-time-only feature. All types are checked at compile time, and errors are generated when there is a mismatch. Mismatches can occur during assignment operations, function calls, and class member dereferencing using the dot (
.) operator. To avoid type
mismatch errors, use strict data typing (see “Strict data typing” on page 24).
Types that you can use include all native object types, classes and interfaces that you define, and Function and Void. The recognized native types are Boolean, Number, and String. All built-in classes are also supported as native types. For more information, see “About data types”
on page 18.
For more information, see “Operator precedence and associativity” on page 32.
Example
Usage 1: The following example declares a public variable named userName whose type is String and assigns an empty string to it:
var userName:String = "";
98 Chapter 5: ActionScript Core Language Elements
Usage 2: The following example shows how to specify a function’s parameter type by defining a function named
function randomInt(integer:Number):Number {
return Math.round(Math.random()*integer); } trace(randomInt(8));
randomInt() that takes a parameter named integer of type Number:
Usage 3: The following example defines a function named squareRoot() that takes a parameter named
val of the Number type and returns the square root of val, also a Number type:
function squareRoot(val:Number):Number {
return Math.sqrt(val); } trace(squareRoot(121));
See Also
var
, function.

?: (conditional)

Availability
Flash Player 4.
Usage
expression1
Parameters
expression1
such as
expression2, expression3 Values of any type.
? expression2 : expression3
An expression that evaluates to a Boolean value; usually a comparison expression,
x < 5.
Returns
The value of expression2 or expression3.
Description
Operator; instructs Flash to evaluate expression1, and if the value of expression1 is true, it returns the value of
expression2; otherwise it returns the value of expression3.
For more information, see “Operator precedence and associativity” on page 32.
Example
The following statement assigns the value of variable x to variable z because expression1 evaluates to
var x:Number = 5; var y:Number = 10; var z = (x < 6) ? x: y; trace (z); // returns 5
true:
?: (conditional) 99
The following example shows a conditional statement written in shorthand:
var timecode:String = (new Date().getHours()<11) ? "AM" : "PM"; trace(timecode);
The same conditional statement could also be written in longhand, as shown in the following example:
if (new Date().getHours()<11) {
var timecode:String = "AM"; } else {
var timecode:String = "PM"; } trace(timecode);

/ (division)

Availability
Flash Player 4.
Usage
expression1 / expression2
Parameters
expression
Returns
A floating-point number.
A number or a variable that evaluates to a number.
Description
Operator (arithmetic); divides expression1 by expression2. The result of the division operation is a double-precision floating-point number.
For more information, see “Operator precedence and associativity” on page 32.
Example
The following statement divides the current width and height of the Stage and then writes the result to the log file.
trace(Stage.width/2); trace(Stage.height/2);
For a Stage width and height of 550 x 400, the output is 275 and 150.
See Also
% (modulo)
100 Chapter 5: ActionScript Core Language Elements
Loading...