MACROMEDIA Flex, FLEX-FLEX ACTIONSCRIPT LANGUAGE Reference

  • Hello! I am an AI chatbot trained to assist you with the MACROMEDIA Flex Reference. I’ve already reviewed the document and can help you find the information you need or explain it in simple terms. Just ask your questions, and providing more details will help me assist you more effectively!
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
3
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
4 Contents
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
5
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 youre new to programming,
ActionScript isnt hard to learn. Its 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.
6 Introduction: Getting Started with ActionScript
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.
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
9
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
10 Chapter 1: ActionScript Basics
Differences between ActionScript and JavaScript
ActionScript is similar to the core JavaScript programming language. You dont 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.
Terminology 11
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
class keyword in a script file.
Constants are elements that dont 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){
this.circumference = 2 * Math.PI * radius;
}
}
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
describe the kind of information a variable or ActionScript element can contain. The
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
x + 2, x and 2 are
operands and
+ 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.
12 Chapter 1: ActionScript Basics
Identifiers are names used to indicate a variable, property, object, function, or method. The first
character must be a letter, underscore (
_), or dollar sign ($). Each subsequent character must be a
letter, number, underscore, or dollar sign. For example,
firstName is the name of a variable.
Instances are objects that contain all the properties and methods of a particular class. For
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
are reserved words that have special meaning. For example, var is a keyword used to
declare local variables. You cannot use a keyword as an identifier. For example,
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.
Syntax 13
Parameters (also called arguments) are placeholders that let you pass values to functions.
For example, the following
welcome() function uses two values it receives in the parameters
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
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
if statement
evaluates a condition to determine the next action that should be taken. The
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
volume
property of the object named
stereoControl:
stereoControl.volume
Variables
are identifiers that hold values of any data type. Variables can be created, changed, and
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
14 Chapter 1: ActionScript Basics
“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 (
book and Book)
are considered different from each other. Therefore, its 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.
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
_x movie clip property indicates a movie clips x axis position. The expression
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
bounce() method of
the
ball object would be called as follows:
ball.bounce();
For more information, see _parent, _global object, and _root.
Syntax 15
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, its 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.
16 Chapter 1: ActionScript Basics
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 dont 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();
};
Syntax 17
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 cant 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
18 Chapter 1: ActionScript Basics
Constants
A constant is a property whose value never changes. ActionScript contains predefined constants.
For example, the constants
BACKSPACE, ENTER, SPACE, and TAB are properties of the Key object
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 cant define your own constants.
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
class declaration is also considered a data type.
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
instanceof operator
(see “Determining an items 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 youve
created. For more information, see “Strict data typing” on page 24.
For more information on Flex data types, see Developing Flex Applications.
About data types 19
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,
"L7" is a string assigned to the variable favoriteBand_str:
var favoriteBand_str:String = "L7";
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:
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 (
+), subtraction (-),
multiplication (
*), division (/), modulo (%), increment (++), and decrement (--). For more
information, see “Numeric operators” on page 33.
Escape sequence Character
\b
Backspace character (ASCII 8)
\f
Form-feed character (ASCII 12)
\n
Line-feed character (ASCII 10)
\r
Carriage return character (ASCII 13)
\t
Tab character (ASCII 9)
\"
Double quotation mark
\'
Single quotation mark
\\
Backslash
\000 - \377
A byte specified in octal
\x00 - \xFF
A byte specified in hexadecimal
\u0000 - \uFFFF
A 16-bit Unicode character specified in hexadecimal
20 Chapter 1: ActionScript Basics
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
true or false. ActionScript also converts the values true
and
false to 1 and 0 when appropriate. Boolean values are most often used with logical
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,
userNameEntered and isPasswordCorrect, and if both
variables evaluate to
true, a welcome message is assigned to the titleMessage String variable.
//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;
//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.
/