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.
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
Macromedia Flex developers can use ActionScript to extend the functionality of their Flex
applications. ActionScript is an ECMAScript-based language that provides support for objectoriented 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 fontindicates 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.
6Introduction: 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.”
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-
• 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.
10Chapter 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.
Terminology11
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
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.
12Chapter 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
Syntax13
• “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.
14Chapter 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.
Syntax15
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();
};
16Chapter 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:
breakcaseclasscontinue
defaultdeletedynamicelse
extendsforfunctionget
ifimplementsimportin
instanceofinterfaceintrinsicnew
privatepublicreturnset
staticswitchthistypeof
varvoidwhilewith
Syntax17
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.
18Chapter 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 sequenceCharacter
\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 types19
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+"!";
For more information, see “Using built-in functions” on page 41 and “Logical operators”
on page 36.
20Chapter 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:
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.
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
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
22Chapter 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 elements23
• “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
24Chapter 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 elements25
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 compiletime 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;
26Chapter 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 variables27
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.
28Chapter 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 variables29
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.
30Chapter 1: ActionScript Basics
Loading...
+ 800 hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.