Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware,
Authorware Star, Backstage, Bright Tiger, Clustercats, ColdFusion, Contribute, Design In Motion, Director, Dream Templates,
Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, Flash Lite, Flex, Fontographer, FreeHand,
Generator, HomeSite, JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track,
LikeMinds, Lingo, Live Effects, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Breeze,
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!, Roundtrip, Roundtrip HTML, Shockwave, Sitespring, SoundEdit, Titlemaker, UltraDev, Web Design 101, what
the web can be, 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.
Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com).
Sorenson™ Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
APPLE COMPUTER, INC. MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, REGARDING THE
ENCLOSED COMPUTER SOFTWARE PACKAGE, ITS MERCHANTABILITY OR ITS FITNESS FOR ANY
PARTICULAR PURPOSE. THE EXCLUSION OF IMPLIED WARRANTIES IS NOT PERMITTED BY SOME STATES.
THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTY PROVIDES YOU WITH SPECIFIC
LEGAL RIGHTS. THERE MAY BE OTHER RIGHTS THAT YOU MAY HAVE WHICH VARY FROM STATE TO
STATE.
Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 are the professional
standard authoring tools for producing high-impact web experiences. ActionScript is the language
you use to add interactivity to a Flash applications, whether your applications are simple animated
movies or more complex rich Internet applications. You don’t have to use ActionScript to use
Flash, but if you want to provide basic or complex user interactivity, work with objects other than
those built into Flash (such as buttons and movie clips), or otherwise turn a SWF file into a more
robust user experience, you’ll probably want to use ActionScript.
Intended audience
This manual assumes that you have already installed Flash MX 2004 or Flash MX Professional
2004 and know how to use it. You should know how to place objects on the Stage and manipulate
them in the Flash authoring environment. 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.
System requirements
ActionScript does not have any system requirements in addition to Flash MX 2004 or Flash MX
Professional 2004. To use ActionScript 2.0, you must use Flash MX 2004.
The documentation assumes that you are using the default publishing settings for your Flash files:
Flash Player 7 and ActionScript 2.0. If you change either of these settings, explanations and code
samples shown in the documentation may not work correctly. If you develop applications for
earlier versions of Flash Player, see “Porting existing scripts to Flash Player 7” on page 13 or
Appendix D, “Writing Scripts for Earlier Versions of Flash Player,” on page 319.
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.
7
• Chapter 1, “What’s New in Flash MX 2004 ActionScript,” on page 11 describes features that
are new in ActionScript, changes to the compiler and debugger, and the new programming
model for the ActionScript 2.0 language.
• Chapter 2, “ActionScript Basics,” on page 23 describes the terminology and basic concepts
used in the rest of the manual.
• Chapter 3, “Using Best Practices,” on page 65 helps explain the best practices for using Flash
and writing ActionScript.
• Chapter 4, “Writing and Debugging Scripts,” on page 139 describes the ActionScript editor
and debugger within Flash that makes it easier to write code.
• Chapter 5, “Handling Events,” on page 167 discusses a few different ways to handle events:
event handler methods, event listeners, and button and movie clip event handlers.
• Chapter 6, “Creating Interaction with ActionScript,” on page 179 describes some simple ways
in which you can create more interactive applications, including controlling when SWF files
play, creating custom pointers, and creating sound controls.
• Chapter 7, “Using the Built-In Classes,” on page 197 lists the built-in classes in ActionScript
and provides a brief overview of how you use them to access powerful features in ActionScript.
• Chapter 8, “Working with Movie Clips,” on page 205 describes movie clips and the
ActionScript you can use to control them.
• Chapter 9, “Working with Text,” on page 221 describes the different ways you can control text
in Flash and include information on text formatting.
• Chapter 10, “Creating Custom Classes with ActionScript 2.0,” on page 247 describes how to
create custom classes and objects for manipulating data in your applications.
• Chapter 11, “Working with External Data,” on page 275 describes how to process data from
external sources using server- or client-side scripts in your applications.
• Chapter 12, “Working with External Media,” on page 295 describes how to import external
media files such as JPEG, MP3, and other SWF files in your Flash applications.
• Appendix A, “Error Messages,” on page 305 contains a list of error messages that the Flash
compiler can generate.
• Appendix B, “Deprecated Flash 4 operators,” on page 311 lists all the ActionScript operators
and their associativity.
• Appendix C, “Keyboard Keys and Key Code Values,” on page 313 lists all the keys on a
standard keyboard and the corresponding ASCII key code values that are used to identify the
keys in ActionScript.
• Appendix D, “Writing Scripts for Earlier Versions of Flash Player,” on page 319 provides
guidelines to help you write scripts that are syntactically correct for the player version you are
targeting.
• Appendix E, “Object-Oriented Programming with ActionScript 1” provides information on
using the ActionScript 1 object model to write scripts.
This manual explains how to use the ActionScript language. For information on the language
elements themselves, see ActionScript Language Reference Help.
8Introduction: Getting Started with ActionScript
Before writing your own scripts, you should complete the lessons “Write Scripts with
ActionScript” and “Create a Form with Conditional Logic and Send Data,” which provide a
hands-on introduction to working with ActionScript. To find these lessons, select Help >
How Do I > Quick Tasks.
When you find information about a certain command you want to use, you can look up its entry
in ActionScript Language Reference Help.
When you find information about a certain command you want to use, you can look up its entry
in Flash ActionScript Language Reference.
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 2, “ActionScript Basics,” on
page 23.
Additional resources
Specific documentation about Flash and related products is available separately.
• For information about the elements that comprise the ActionScript language, see ActionScript
Language Reference Help.
• For information about working in the Flash authoring environment, see Using Flash Help.
• For information about working with components, see Using Components Help.
• For information about creating communication applications with Flash Communication
Server, see Developing Communications Applications and Managing Flash Communication Server.
• For information about accessing web services with Flash applications, see Using Flash Remoting.
You can find application FLA files that use common Flash functionality installed with Flash.
These applications were designed to introduce new Flash developers to the capabilities of Flash
applications as well as show advanced developers how Flash features work in context. On
Windows, you can find the applications in \Program Files\Macromedia\Flash MX 2004\
Examples. On the Macintosh, you can find the applications in HD/Applications/Macromedia
Flash MX 2004/Examples.
Additional resources9
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.
10Introduction: Getting Started with ActionScript
CHAPTER 1
What’s New in Flash MX 2004 ActionScript
Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 provide several
enhancements that make it easy for you to write robust scripts using the ActionScript language.
The new features, which are discussed in this chapter, include new language elements, improved
editing and debugging tools (see “ActionScript editor changes” on page 20 and “Debugging
changes” on page 21), and the introduction of a more object-oriented programming model (see
“New object-oriented programming model” on page 21).
This chapter also contains an extensive section that you should read carefully if you plan to
publish any of your existing Flash MX or earlier files to Flash Player 7 (see “Porting existing
scripts to Flash Player 7” on page 13).
Updating Flash XML files
It is important that you always have the latest Flash XML files installed. Macromedia sometimes
introduces features in dot releases (minor releases) of Flash Player. When such a release is
available, you should update your version of Flash to get the latest XML files. Otherwise, the
Flash MX 2004 compiler might generate errors if you use new properties or methods that were
unavailable in the version of Flash Player that came with your Flash installation.
For example, Flash Player 7 (7.0.19.0) contained a new method for the System object,
System.security.loadPolicyFile. To access this method, you must use the Player Updater
installer to update all the Flash Players that are installed with Flash. Otherwise, the Flash MX
2004 compiler displays errors.
Remember that you can install a Player Updater that is one or more major versions ahead of your
version of Flash. By doing this, you will get the XML files that you need but shouldn’t have any
compiler errors when you publish to older versions of Flash Player. Sometimes new methods or
properties are available to older versions, and having the latest XML files minimizes the compiler
errors you get when you try to access older methods or properties.
11
New and changed language elements
This section describes the ActionScript language elements that are new or changed in Flash MX
2004. To use any of these elements in your scripts, you must target Flash Player 7 (the default)
when you publish your documents.
• The Array.sort() and Array.sortOn() methods let you add parameters to specify
additional sorting options, such as ascending and descending sorting, whether to consider casesensitivity when sorting, and so on.
• The Button.menu, MovieClip.menu, and TextField.menu properties work with the new
ContextMenu and ContextMenuItem classes to let you associate context menu items with
Button, MovieClip, or TextField objects.
• The “ContextMenu class” and “ContextMenuItem class” let you customize the context menu
that appears when a user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.
• The “Error class” and the throw and try..catch..finally commands let you implement
more robust exception handling.
• The LoadVars.addRequestHeader() and XML.addRequestHeader() methods add or change
HTTP request headers (such as
Content-Type or SOAPAction) sent with POST actions.
• The MMExecute() function lets you issue Flash JavaScript API commands from ActionScript.
• The Mouse.onMouseWheel event listener is generated when the user scrolls using the mouse
wheel (Windows only).
• The MovieClip.getNextHighestDepth() method lets you create MovieClip instances at
runtime and be guaranteed that their objects render in front of the other objects in a parent
movie clip’s z-order space.
• The MovieClip.getInstanceAtDepth() method lets you access dynamically created
MovieClip instances using the depth as a search index.
• The MovieClip.getSWFVersion() method lets you determine which version of Flash Player
is supported by a loaded SWF file.
• The MovieClip.getTextSnapshot() method and the “TextSnapshot object” let you work
with text that is in static text fields in a movie clip.
• The MovieClip._lockroot property lets you specify that a movie clip will act as _root for
any movie clips loaded into it or that the meaning of
movie clip is loaded into another movie clip.
_root in a movie clip won’t change if that
• The “MovieClipLoader class” lets you monitor the progress of files as they are loaded into
movie clips.
• The “NetConnection class” and “NetStream class” let you stream local Flash video (FLV) files.
• The “PrintJob class” gives you (and the user) more control over printing from Flash Player.
• The Sound.onID3 event handler provides access to ID3 data associated with a Sound object
that contains an MP3 file.
• The Sound.id3 property provides access to the metadata that is part of an MP3 file.
• The “System class” has new objects and methods, and the “System.capabilities object” has
several new properties.
12Chapter 1: What’s New in Flash MX 2004 ActionScript
• The TextField.condenseWhite property lets you remove extra white space from HTML text
fields that are rendered in a browser.
• The TextField.mouseWheelEnabled property lets you specify whether a text field’s contents
should scroll when the mouse pointer is positioned over a text field and the user rolls the
mouse wheel.
• The “TextField.StyleSheet class” lets you create a style sheet object that contains text
formatting rules such as font size, color, and other formatting styles.
• The TextField.styleSheet property lets you attach a style sheet object to a text field.
• The TextFormat.getTextExtent() method accepts a new parameter, and the object it
returns contains a new member.
• The XML.addRequestHeader() method lets you add or change HTTP request headers (such
as
Content-Type or SOAPAction) sent with POST actions.
New security model and legacy SWF files
Rules for how Flash Player determines whether two domains are the same have changed in Flash
Player 7. In addition, rules that determine whether and how a SWF file served from an HTTP
domain can access a SWF file or load data from an HTTPS domain have changed. In most cases,
these changes won’t affect you unless you are porting your existing SWF files to Flash Player 7.
However, if you have SWF files published for Flash Player 6 or earlier that load data from a file
stored on a server, and the calling SWF file is playing in Flash Player 7, the user might see a dialog
box that didn’t appear before, asking whether to allow access. You can prevent this dialog box
from appearing by implementing a policy file on the site where the data is stored. For more
information on this dialog box, see “About compatibility with previous Flash Player security
models” on page 294.
You might also need to implement a policy file if you are using runtime shared libraries. If either
the loading or loaded SWF file is published for Flash Player 7 and the loading and loaded files
aren’t served from the exact same domain, use a policy file to permit access. For more information
on policy files, see “About allowing cross-domain data loading” on page 290.
Porting existing scripts to Flash Player 7
As with any new release, Flash Player 7 supports more ActionScript commands than previous
versions of the player; you can use these commands to implement more robust scripts. (See “New
and changed language elements” on page 12.)However, if you used any of these commands in
your existing scripts, the script might not work correctly if you publish it for Flash Player 7.
For example, if you have a script with a function named
compile correctly but might not run as expected in Flash Player 7, because
class (making it a reserved word) in ActionScript. You can fix your script by renaming the Error
function to something else, such as
“Keywords and reserved words” on page 32.
ErrorCondition. For a complete list of reserved words, see
Error, the script might appear to
Error is now a built-in
Porting existing scripts to Flash Player 713
Also, Flash Player 7 implements several changes that affect how one SWF file can access another
SWF file, how external data can be loaded, and how local settings and data (such as privacy
settings and locally persistent shared objects) can be accessed. Finally, the behavior of some
existing features has changed.
If you have existing scripts written for Flash Player 6 or earlier that you want to publish for Flash
Player 7, you might need to modify the scripts so they conform with the implementation of Flash
Player 7 and work as designed. These modifications are discussed in this section under the
following headings:
• “ECMA-262 compliance” on page 14
• “Domain-name rules for settings and local data” on page 15
• “Cross-domain and subdomain access between SWF files” on page 15
• “HTTP to HTTPS protocol access between SWF files” on page 18
• “Server-side policy files for permitting access to data” on page 19
ECMA-262 compliance
Several changes were implemented in Flash Player 7 to conform more closely to the ECMA-262
Edition 3 standard (see www.ecma-international.org/publications/standards/Ecma-262.htm). In
addition to the class-based programming techniques available in ActionScript 2.0 (see “New
object-oriented programming model” on page 21), other features have been added and certain
behaviors have changed. Also, when publishing for Flash Player 7 and using ActionScript 2.0, you
can cast one object type to another. For more information, see “Casting objects” on page 42.
These capabilities don’t require you to update existing scripts; however, you might want to use
them if you publish your scripts to Flash Player 7 and then continue to revise and enhance them.
Unlike the changes mentioned above, the changes listed in the following table (some of which
also improve ECMA compliance) can cause existing scripts to work differently than they did
before. If you used these features in existing scripts that you want to publish to Flash Player 7,
review the changes to make sure your code still works as intended or to determine whether you
need to rewrite your code. In particular, because
cases, you should initialize all variables in scripts that you port to Flash Player 7.
undefined is evaluated differently in certain
SWF file published for Flash Player 7SWF file published for earlier versions of
Flash Player
Case-sensitivity is enforced (variable names that
differ only in capitalization are interpreted as being
different variables). This change also affects files
loaded with
with
“Case sensitivity” on page 28.
Evaluating
NaN.
myCount +=1;
trace(myCount); // NaN
14Chapter 1: What’s New in Flash MX 2004 ActionScript
#include and external variables loaded
LoadVars.load(). For more information, see
undefined in a numeric context returns
Case-sensitivity is not supported (variable
names that differ only in capitalization are
interpreted as being the same variable).
Evaluating undefined in a numeric context
returns 0.
myCount +=1;
trace(myCount); // 1
SWF file published for Flash Player 7SWF file published for earlier versions of
Flash Player
When undefined is converted to a string, the result is
In Flash Player 6, superdomain matching rules are used by default when accessing local settings
(such as camera or microphone access permissions) or locally persistent data (shared objects).
That is, the settings and data for SWF files hosted at here.xyz.com, there.xyz.com, and xyz.com
are shared and are all stored at xyz.com.
In Flash Player 7, exact-domain matching rules are used by default. That is, the settings and data
for a file hosted at here.xyz.com are stored at here.xyz.com, the settings and data for a file hosted
at there.xyz.com are stored at there.xyz.com, and so on.
A new property,
System.exactSettings, lets you specify which rules to use. This property is
supported for files published for Flash Player 6 or later. For files published for Flash Player 6, the
default value is
Flash Player 7, the default value is
false, which means superdomain matching rules are used. For files published for
true, which means exact-domain matching rules are used.
If you use settings or persistent local data and want to publish a Flash Player 6 SWF file for Flash
Player 7, you might need to set this value to
For more information, see
System.exactSettings in Flash ActionScript Language Reference
false in the ported file.
Help.
Cross-domain and subdomain access between SWF files
When you develop a series of SWF files that communicate with each other—for example, when
using
loadMovie(), MovieClip.loadMovie(), MovieClipLoader.LoadClip(), or Local
Connection objects—you might host the SWF files in different domains or in different
subdomains of a single superdomain.
Porting existing scripts to Flash Player 715
In files published for Flash Player 5 or earlier, there were no restrictions on cross-domain or
subdomain access.
In files published for Flash Player 6, you could use the
or
System.security.allowDomain() method to specify permitted cross-domain access (for
LocalConnection.allowDomain handler
example, to let a file at someSite.com be accessed by a file at someOtherSite.com), and no
command was needed to permit subdomain access (for example, a file at www.someSite.com
could be accessed by a file at store.someSite.com).
Files published for Flash Player 7 implement access between SWF files differently from earlier
versions in two ways. First, Flash Player 7 implements exact-domain matching rules instead of
superdomain matching rules. Therefore, the file being accessed (even if it is published for a Player
version earlier than Flash Player 7) must explicitly permit cross-domain or subdomain access; this
topic is discussed in this section. Second, a file hosted at a site using a secure protocol (HTTPS)
must explicitly permit access from a file hosted at a site using an insecure protocol (HTTP or
FTP); this topic is discussed in the next section (see “HTTP to HTTPS protocol access between
SWF files” on page 18).
The following table summarizes domain-matching rules in different versions of Flash Player:
Files published forCross-domain access between
SWF files
Flash Player 5 or earlier No restrictionsNo restrictions
Flash Player 6Superdomain matchingNo restrictions
Flash Player 7Exact domain matching
Explicit permission for HTTPShosted files to access HTTP- or
FTP-hosted files
Subdomain access between SWF
files
Exact domain matching
Explicit permission for HTTPShosted files to access HTTP- or
FTP-hosted files
Because Flash Player 7 implements exact-domain matching rules instead of superdomain
matching rules, you might have to modify existing scripts if you want to access them from files
that are published for Flash Player 7. (You can still publish the modified files for Flash Player 6.)
If you used any
LocalConnection.allowDomain() or System.security.allowDomain()
statements in your files and specified superdomain sites to permit, you must change your
parameters to specify exact domains instead. The following code shows an example of changes
you might have to make:
// Flash Player 6 commands in a SWF file at www.anyOldSite.com
// to allow access by SWF files that are hosted at www.someSite.com
// or at store.someSite.com
System.security.allowDomain("someSite.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="someSite.com");
}
// Corresponding commands to allow access by SWF files
// that are published for Flash Player 7
System.security.allowDomain("www.someSite.com", "store.someSite.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="www.someSite.com" ||
sendingDomain=="store.someSite.com");
}
16Chapter 1: What’s New in Flash MX 2004 ActionScript
You might also have to add statements such as these to your files if you aren’t currently using
them. For example, if your SWF file is hosted at www.someSite.com and you want to allow access
by a SWF file published for Flash Player 7 at store.someSite.com, you must add statements such
as the following example to the file at www.someSite.com (you can still publish the file at
www.someSite.com for Flash Player 6):
In addition, consider that if a Flash Player 6 application running within Flash Player 7 tries to
access data outside its exact domain, Flash Player 7 domain-matching rules are enforced and the
user is prompted to allow or deny access.
To summarize, you might have to modify your files to add or change
allowDomain statements if
you publish files for Flash Player 7 that meet the following conditions:
• You implemented cross-SWF scripting (using loadMovie(), MovieClip.loadMovie(),
MovieClipLoader.LoadClip(), or Local Connection objects).
• The called SWF file (of any version) is not hosted at a site using a secure protocol (HTTPS), or
the calling and called SWF files are both hosted at HTTPS sites. (If only the called SWF file is
HTTPS, see “HTTP to HTTPS protocol access between SWF files” on page 18.)
• The SWF files are not in same domain (for example, one file is at www.domain.com and one is
at store.domain.com).
You must make the following changes:
• If the called SWF file is published for Flash Player 7, include System.security.allowDomain
or
LocalConnection.allowDomain in the called SWF file, using exact domain-
name matching.
• If the called SWF file is published for Flash Player 6, modify the called file to add or change a
System.security.allowDomain or LocalConnection.allowDomain statement, using exact
domain-name matching, as shown in the code examples earlier in this section. You can publish
the modified file for either Flash Player 6 or 7.
• If the called SWF file is published for Flash Player 5 or earlier, port the called file to
Flash Player 6 or 7 and add a
domain-name matching, as shown in the code examples earlier in this section.
(LocalConnection objects aren’t supported in Flash Player 5 or earlier.)
For more information, see the tech note at www.macromedia.com/support/flash/ts/documents/
security_sandbox.htm.
System.security.allowDomain statement, using exact
Porting existing scripts to Flash Player 717
HTTP to HTTPS protocol access between SWF files
As discussed in the previous section, rules for cross-domain and subdomain access have changed
in Flash Player 7. In addition to the exact-domain matching rules now being implemented, you
must explicitly permit files hosted at sites using a secure protocol (HTTPS) to be accessed by files
hosted at sites using an insecure protocol. Depending on whether the called file is published for
Flash Player 7 or 6, you must implement either one of the
allowDomain statements (see “Cross-
domain and subdomain access between SWF files” on page 15), or use the new
LocalConnection.allowInsecure Domain or System.security.allowInsecureDomain()
statements.
Warning: Implementing an allowInsecureDomain() statement compromises the security offered
by the HTTPS protocol. You should make these changes only if you can’t reorganize your site so that
all SWF files are served from the HTTPS protocol.
The following code shows an example of the changes you might have to make:
// Commands in a Flash Player 6 SWF file at https://www.someSite.com
// to allow access by Flash Player 7 SWF files that are hosted
// at http://www.someSite.com or at http://www.someOtherSite.com
System.security.allowDomain("someOtherSite.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="someOtherSite.com");
}
// Corresponding commands in a Flash Player 7 SWF file
// to allow access by Flash Player 7 SWF files that are hosted
// at http://www.someSite.com or at http://www.someOtherSite.com
System.security.allowInsecureDomain("www.someSite.com",
You might also have to add statements such as these to your files if you aren’t currently using
them. A modification might be necessary even if both files are in same domain (for example, a file
in http://www.domain.com is calling a file in https://www.domain.com).
To summarize, you might have to modify your files to add or change statements if you publish
files for Flash Player 7 that meet the following conditions:
• You implemented cross-SWF scripting (using loadMovie(), MovieClip.loadMovie(),
MovieClipLoader.LoadClip(), or Local Connection objects).
• The calling file is not hosted using an HTTPS protocol, and the called file is HTTPS.
You must make the following changes:
• If the called file is published for Flash Player 7, include
System.security.allowInsecureDomain or LocalConnection.allowInsecureDomain in
the called file, using exact domain-name matching, as shown in the code examples earlier in
this section. This statement is required even if the calling and called SWF files are in
same domain.
18Chapter 1: What’s New in Flash MX 2004 ActionScript
• If the called file is published for Flash Player 6 or earlier, and both the calling and called files
are in same domain (for example, a file in http://www.domain.com is calling a file in https://
www.domain.com), no modification is needed.
• If the called file is published for Flash Player 6, the files are not in same domain, and you don’t
want to port the called file to Flash Player 7, modify the called file to add or change a
System.security.allowDomain or LocalConnection.allowDomain statement, using exact
domain-name matching, as shown in the code examples earlier in this section.
• If the called file is published for Flash Player 6 and you want to port the called file to Flash
Player 7, include
LocalConnection.allowInsecureDomain in the called file, using exact domain-name
matching, as shown in the code examples earlier in this section. This statement is required even
if both files are in same domain.
System.security.allowInsecureDomain or
• If the called file is published for Flash Player 5 or earlier, and both files are not in the same
domain, you can do one of two things. You can either port the called file to Flash Player 6 and
add or change a
matching, as shown in the code examples earlier in this section, or you can port the called file
to Flash Player 7, and include a
called file, using exact domain-name matching, as shown in the code examples earlier in
this section.
Server-side policy files for permitting access to data
A Flash document can load data from an external source by using one of the following data
loading calls:
NetServices.createGatewayConnection). Also, a SWF file can import runtime shared
libraries (RSLs), or assets defined in another SWF file, at runtime. By default, the data or RSL
must reside in the same domain as the SWF file that is loading that external data or media.
System.security.allowDomain statement, using exact domain-name
System.security.allowInsecureDomain statement in the
XML.load(), XML.sendAndLoad(), LoadVars.load(),
, XMLSocket.connect(), and Macromedia Flash Remoting
To make data and assets in runtime shared libraries available to SWF files in different domains,
you should use a cross-domain policy file. A cross-domain policy file is an XML file that provides a
way for the server to indicate that its data and documents are available to SWF files served from
certain domains, or from all domains. Any SWF file that is served from a domain specified by the
server’s policy file is permitted to access data or RSLs from that server.
If you are loading external data, you should create policy files even if you don’t plan to port any
files to Flash Player 7. If you are using RSLs, you should create policy files if either the calling or
called file is published for Flash Player 7.
For more information, see “About allowing cross-domain data loading” on page 290.
Porting existing scripts to Flash Player 719
ActionScript editor changes
The ActionScript editor has been updated in several ways to make it more robust and easier to
use. These changes are summarized in this section.
Word wrapping You can now use the Options pop-up menu in the Script pane, Debugger
panel, and Output panel to enable or disable word wrapping. You can also toggle word wrapping
using the pop-up menu on the Actions panel. The keyboard shortcut is Control+Shift+W
(Windows) or Command+Shift+W (Macintosh).
Viewing context-sensitive help When your pointer is positioned over an ActionScript
language element in the Actions toolbox or in the Script pane, you can use the View Help item in
the context menu to display a help page about that element.
Importing scripts When you select Import Script from the pop-up menu in the Actions panel,
the imported script is copied into the script at the insertion point in your code file. In previous
versions of Flash, importing a script overwrote the contents of the existing script.
Single-click breakpoints To add a debugging breakpoint before a line of code in the Debugger
panel or the Script pane on the Actions panel, you can click in the left margin. In previous
versions of Flash, clicking in the left margin selected a line of code. The new way to select a line of
code is to Control-click (Windows) or Command-click (Macintosh).
Normal and expert modes no longer in Actions panel In previous versions of Flash, you could
work in the Actions panel either in normal mode, in which you filled in options and parameters
to create code, or in expert mode, in which you added commands directly into the Script pane. In
Flash MX 2004 and Flash MX Professional 2004, you can work in the Actions panel only by
adding commands directly to the Script pane. You can still drag commands from the Actions
toolbox into the Script pane or use the Add (+) button above the Script pane to add commands to
a script.
Pinning multiple scripts You can pin multiple scripts within a FLA file along the bottom of the
Script pane in the Actions panel. In previous versions of Flash, you could pin only one script at
a time.
Script navigator The left side of the Actions panel now contains two panes: the Actions toolbox
and a new Script navigator. The Script navigator is a visual representation of the structure of your
FLA file; you can navigate through your FLA file here to locate ActionScript code.
Integrated Script window for editing external files (Flash Professional only) You can use the
ActionScript editor in a Script window (separate from the Actions panel) to write and edit
external script files. Syntax coloring, code hinting, and other preferences are supported in the
Script window, and the Actions toolbox is also available. To display the Script window, use
File > New, and select the type of external file you want to edit. You can have multiple external
files open at the same time; filenames appear on tabs across the top of the Script window. (The
tabs appear only in Windows.)
20Chapter 1: What’s New in Flash MX 2004 ActionScript
Debugging changes
This section describes changes that improve your ability to debug your scripts.
Output window changed to Output panel You can now move and dock the Output panel in
the same way as any other panel in Flash.
Improved error reporting at compile time In addition to providing more robust exception
handling, ActionScript 2.0 provides several new compile-time errors. For more information, see
Appendix A, “Error Messages,” on page 305.
Improved exception handling The Error class and the throw and try..catch..finally
commands let you implement more robust exception handling.
New object-oriented programming model
The ActionScript language has grown and developed since its introduction several years ago. With
each new release of Flash, additional keywords, objects, methods, and other language elements
have been added to the language. However, unlike earlier releases of Flash, Flash MX 2004 and
Flash MX Professional 2004 introduce several new language elements that implement objectoriented programming in a more standard way than before. Because these language elements
represent a significant enhancement to the core ActionScript language, they represent a new
version of ActionScript: ActionScript 2.0.
ActionScript 2.0 is not a new language. Rather, it comprises a core set of language elements that
make it easier to develop object-oriented programs. With the introduction of keywords such as
class, interface, extends, and implements, ActionScript syntax is now easier to learn for
programmers who are familiar with other languages. New programmers can learn more standard
terminology that they can apply to other object-oriented languages they might study in the
future.
The object-oriented programming (OOP) features in ActionScript 2.0 are based on the
ECMAScript 4 Draft Proposal currently in development by ECMA TC39-TG1 (see
www.mozilla.org/js/language/es4/index.html). Because the ECMA-4 proposal is not yet a
standard, and because it is still changing, ActionScript 2.0 does not conform exactly to this
specification.
ActionScript 2.0 supports all the standard elements of the ActionScript language; it lets you write
scripts that more closely adhere to standards used in other object-oriented languages, such as Java.
ActionScript 2.0 should be of interest primarily to intermediate or advanced Flash developers
who are building applications that require the implementation of classes and subclasses.
ActionScript 2.0 also lets you declare the object type of a variable when you create it (see “Strict
data typing” on page 41) and provides significantly improved compiler errors (see Appendix A,
“Error Messages,” on page 305).
The following list shows the language elements that are new in ActionScript 2.0:
• class
• extends
• implements
New object-oriented programming model21
• interface
• dynamic
• static
• public
• private
• get
• set
• import
Key facts about ActionScript 2.0 include the following points:
• Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external script
files, with a single class defined in each script; that is, classes and interfaces cannot be defined
in the Actions panel.
• You can import individual class files implicitly (by storing them in a location specified by
global or document-specific search paths and then using them in a script) or explicitly (by
using the
by using wildcards.
import command); you can import packages (collections of class files in a directory)
• Applications developed with ActionScript 2.0 are supported by Flash Player 6 and later.
Caution: The default publish setting for new files created in Flash MX 2004 is ActionScript 2.0. If
you plan to modify an existing FLA file to use ActionScript 2.0 syntax, ensure that the FLA file
specifies ActionScript 2.0 in its publish settings. If it does not, your file will compile incorrectly,
although Flash will not generate compiler errors.
For more information on using ActionScript 2.0 to write object-oriented programs in Flash, see
Chapter 10, “Creating Custom Classes with ActionScript 2.0,” on page 247.
Although using ActionScript 2.0 is recommended, you can continue to use ActionScript 1 syntax,
especially if you are doing more traditional Flash work such as simple animation that doesn’t
require user interaction.
22Chapter 1: What’s New in Flash MX 2004 ActionScript
CHAPTER 2
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 Flash ActionScript Language Reference. Applying the basics of ActionScript in a way that creates elegant programs can
be a challenge for users who are new to ActionScript. For more information on how to apply the
rules described in this section, see “Using Best Practices” on page 65.
This section contains the following topics:
• “Differences between ActionScript and JavaScript” on page 24
• “Terminology” on page 24
• “Syntax” on page 28
• “About data types” on page 34
• “Assigning data types to elements” on page 39
• “About variables” on page 44
• “Using operators to manipulate values in expressions” on page 49
• “Specifying an object’s path” on page 57
• “Using condition statements” on page 58
• “Using built-in functions” on page 60
• “Creating functions” on page 61
23
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.
• ActionScript 2.0, the latest version of the ActionScript language, 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.
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
Actions panel).
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.
24Chapter 2: ActionScript Basics
class keyword in an external script file (not in a script you are writing in the
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 34.
Events are actions that occur while a SWF file is playing. For example, different events are
generated when a movie clip loads, the playhead enters a frame, 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. (There are also
two event handlers,
on() and onClipEvent(), that you can assign directly to buttons and movie
clips.) In the Actions toolbox, each ActionScript object that has event handler methods or event
listeners has a subcategory called Events or 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 “Handling Events” on page 167.
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
+ is an operator.
x + 2, x and 2 are
Functions are blocks of reusable code that can be passed parameters and can return a value. For
more information, see “Creating functions” on page 61.
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.
Terminology25
Instance names are unique names that let you target instances you create, or movie clip and
button instances on the Stage. 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();
You use the Property inspector to assign instance names to instances on the Stage. For example, a
master symbol in the library could be called
the SWF file could have the instance names
following code sets a variable called
You can use strict data typing when creating instances so that code hints (see “Using code hints”
on page 147) appear as you type your code. For more information, see “Strictly typing objects to
trigger code hints” on page 145.
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 32.
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.
26Chapter 2: ActionScript Basics
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.
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 268).
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 name a movie clip instance in the movie clip Property inspector. (The main
Timeline always has the name
_root.) 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
stereoControl.volume
volume property of the object named stereoControl:
For more information on target paths, see “Using absolute and relative target paths” in Using
Flash.
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 44.
Terminology27
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 28
• “Dot syntax” on page 29
• “Slash syntax” on page 30
• “Curly braces” on page 30
• “Semicolons” on page 31
• “Parentheses” on page 31
• “Comments” on page 31
• “Keywords and reserved words” on page 32
• “Constants” on page 34
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.
When you publish files for Flash Player 7 or later, Flash implements case sensitivity whether you
are using ActionScript 1 or ActionScript 2.0. This means that keywords, class names, variables,
method names, and so on are all case sensitive. For example:
// In file targeting Flash Player 7
// and either ActionScript 1 or ActionScript 2.0
//
// Sets properties of two different objects
cat.hilite = true;
CAT.hilite = true;
book and Book)
// Creates three different variables
var myVar:Number=10;
var myvar:Number=10;
var mYvAr:Number=10;
// Does not generate an error
var array:Array = new Array();
var date:Date = new Date();
This change also affects external variables loaded with LoadVars.load().
Case-sensitivity is implemented for external scripts, such as ActionScript 2.0 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.
28Chapter 2: ActionScript Basics
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.
When syntax coloring is enabled, language elements written with correct capitalization are blue
by default. For more information, see “Keywords and reserved words” on page 32 and “Syntax
highlighting” on page 144.
Dot syntax
In ActionScript, a dot (
.) is used to access properties or methods belonging to an object or movie
clip. It is also used to identify the target path to a movie clip, variable, function, or object. A dot
syntax expression begins with the name of the object or movie clip followed by a dot and ends
with the element you want to specify.
For example, the
expression
As another example,
movie clip
variable of the instance
_x movie clip property indicates a movie clip’s x axis position on the Stage. The
ball_mc._x refers to the _x property of the movie clip instance ball_mc.
submit is a variable set in the form movie clip, which is nested inside the
shoppingCart. The expression shoppingCart.form.submit = true sets the submit
form to true.
Expressing a method of an object or movie clip follows the same pattern. For example, the
bounce() method of the ball object would be called as follows:
ball.bounce();
Dot syntax also uses three special aliases, _root,_parent, and _global. The alias _root refers
to the main Timeline. You can use the
the following statement calls the function
_root alias to create an absolute target path. For example,
buildGameBoard() in the movie clip functions on
the main Timeline:
_root.functions.buildGameBoard();
You can use the alias _parent to refer to a movie clip in which the current object is nested. You
can also use
nested inside the movie clip
animal_mc to stop:
this._parent.stop();
_parent to create a relative target path. For example, if the movie clip dog_mc is
animal_mc, the following statement on the instance dog_mc tells
You can use the alias _global to indicate, without having to use a target path, that an object is
available to all Timelines in your document. For example, the following statement defines the
function
_global.response = function() {
}
response that is available to all Timelines:
if (myVar <= 19) {
myResponse = "25% discount for 20 or more orders";
} else {
myResponse = "Thanks for your order";
}
For more information, see _parent, _global object, and _root. in Flash ActionScript Language
Reference.
Syntax29
Slash syntax
Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. This
syntax is still supported by Flash Player 7, but its use is not recommended, and slash syntax is not
supported in ActionScript 2.0. However, if you are creating content intended specifically for
Flash Player 4, you must use slash syntax. For more information, see “Using slash syntax”
on page 321.
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. For recommended guidelines on formatting
code, see Chapter 3, “Formatting code,” on page 76.
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;
}
You can check for matching curly braces in your scripts (see “Checking syntax and punctuation”
on page 150).
30Chapter 2: ActionScript Basics
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.
Semicolons are required within
//For loop that adds numbers 1-10
var sum:Number = 0;
for (var i=1; i<=10; i++) {
sum += i;
}
for loops, as shown in the following example:
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 49.)
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);
You can check for matching parentheses in your scripts; see “Checking syntax and punctuation”
on page 150. For recommended guidelines on formatting and parentheses, see Chapter 3,
“Writing syntax and statements,” on page 89.
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.
Syntax31
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();
};
//):
When syntax coloring is enabled (see “Syntax highlighting” on page 144), comments are gray by
default. 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;
For recommended guidelines on formatting and parentheses, see Chapter 3, “Using comments in
code,” on page 77.
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:
addandbreakcase
catchclasscontinuedefault
deletedodynamicelse
32Chapter 2: ActionScript Basics
eqextendsfinallyfor
functiongegetgt
ififFrameLoadedimplementsimport
ininstanceofinterfaceintrinsic
leltnenew
notononClipEventor
privatepublicreturnset
staticswitchtellTargetthis
throwtrytypeofvar
voidwhilewith
All class names, component class names, and interface names are reserved words:
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 35
• “Number data type” on page 36
• “Boolean data type” on page 36
• “Object data type” on page 37
• “MovieClip data type” on page 37
• “Null data type” on page 39
• “Undefined data type” on page 39
• “Void data type” on page 39
ActionScript also has built-in classes, such as Array and Date, that can be considered complex
data types. For more information, see “Using the Built-In Classes” on page 197. If you are an
advanced developer, you might create custom classes. Any class that you define using the
declaration is also considered a data type. All built-in data types and classes are fully defined in
Flash ActionScript Language Reference.
class
Variables containing primitive data types behave differently in certain situations than those
containing reference types. (See “Using variables in a program” on page 47.) 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 43).
34Chapter 2: ActionScript Basics
instanceof operator
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 41.
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. For information on the methods and properties of
the String class, see the “String class” entry in Flash ActionScript Language Reference.
About data types35
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 51.
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 in Flash ActionScript Language Reference.
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;
//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+"!";
36Chapter 2: ActionScript Basics
true, a welcome message is assigned to the titleMessage String variable.
userNameEntered and isPasswordCorrect, and if both
For more information, see “Using built-in functions” on page 60 and “Logical operators”
on page 53.
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
The ActionScript MovieClip object has methods that let you control movie clip symbol instances
on the Stage. This example uses the
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; the number of frames loaded; 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 250.
.)
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.
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
For more information, see “Working with Movie Clips” on page 205 and the “MovieClip class”
entry in Flash ActionScript Language Reference.
38Chapter 2: ActionScript Basics
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
Several methods and functions return
demonstrates how you can use
if (Selection.getFocus() == null) {
trace("no selection");
}
Undefined data type
null if no value has been set. The following example
null to test if form fields currently have form focus:
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
Assigning data types to elements39
• 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 40
• “Strict data typing” on page 41
• “Casting objects” on page 42
• “Determining an item’s data type” on page 43
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 41.
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
automatically converts the value to a string and sends it to the Output panel.
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 41.
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()
+) operator expects the other operand to be
40Chapter 2: ActionScript Basics
Strict data typing
ActionScript 2.0 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
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 45).
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 is
expecting a Boolean value.
Assigning data types to elements41
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.
Another advantage of strict data typing is that Flash MX 2004 automatically shows code hints for
built-in objects when they are strictly typed. For more information, see “Strictly typing objects to
trigger code hints” on page 145.
Files published using ActionScript 1 do not respect strict data typing assignments at compile
time, so assigning the wrong type of value to a variable that you have strictly typed doesn’t
generate a compiler error.
var x:String = "abc"
x = 12 ; // no error in ActionScript 1, type mismatch error in ActionScript 2
The reason for this is that when you publish a file for ActionScript 1, Flash interprets a statement
such as
var x:String = "abc" as slash syntax rather than as strict typing. (ActionScript 2.0
doesn’t support slash syntax.) This behavior can result in an object that is assigned to a variable of
the wrong type, causing the compiler to let illegal method calls and undefined property references
pass through unreported.
Therefore, if you are implementing strict data typing, make sure you are publishing files for
ActionScript 2.0.
Casting objects
ActionScript 2.0 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.
The syntax for casting is
of
item is type. Casting is essentially a function call, and the function call returns null if the cast
type(item), where you want the compiler to behave as if the data type
fails at runtime (in files published for Flash Player 7 or later; files published for Flash Player 6 do
not have runtime support for failed casts). 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
42Chapter 2: ActionScript Basics
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 the entry for each conversion function in Flash ActionScript Language Reference:
Array(), Boolean(), Number(), Object(), 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;
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);
For more information about these operators, see typeof and instanceof in Flash ActionScript
Language Reference. For more information on testing and debugging, see Chapter 4, “Writing and
Debugging Scripts,” on page 139.
Assigning data types to elements43
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 and is often done in the first frame of the SWF file. 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. Flash Player 7 and later evaluate uninitialized variables
differently than Flash Player 6 and earlier. If you have written scripts for Flash Player 6 and plan
to write or port scripts for Flash Player 7 or later, you should be understand these differences to
avoid unexpected behavior. For more information, see “ECMA-262 compliance” on page 14.
Variables can hold any type of data (see “About data types” on page 34). 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
For example,
panel in test mode. You can also check and set the variable values in the Debugger in test mode.
For more information, see “Using the trace statement” on page 165 and “Displaying and
modifying variables” on page 157.
For more information, see the following topics:
trace(hoursWorked) sends the value of the variable hoursWorked to the Output
trace() statement to send the value to the Output panel.
• “Naming a variable” on page 44
• “Scoping and declaring variables” on page 45
• “Using variables in a program” on page 47
Naming a variable
A variable’s name must follow these rules:
• It must be an identifier (see “Terminology” on page 24).
• It cannot be a keyword or an ActionScript literal such as true, false, null, or undefined.
(See Chapter 3, “Avoiding reserved words,” on page 75).
• It must be unique within its scope (see “Scoping and declaring variables” on page 45).
44Chapter 2: ActionScript Basics
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:
String
The ActionScript editor supports code hints for built-in classes and for variables that are based on
these classes. If you want Flash to provide code hints for a particular object type that is assigned to
a variable, you can strictly type the variable.
For example, suppose you type the following code:
var members:Array = new Array();
members.
As soon as you type the period (.), Flash displays a list of methods and properties available for
Array objects.
Another way to tell Flash to provide code hints is to name the variable using a specific suffix. For
more information on using strict typing and suffixes, see “Writing code that triggers code hints”
on page 145. For information and detailed guidelines on naming variables, see Chapter 3,
“General naming guidelines,” on page 69.
Scoping and declaring variables
A variable’s scope refers to the area in which the variable is known and can be referenced. There are
three types of variable scopes in ActionScript:
• Timeline variables are available to any script on that Timeline.
• Local variables are available within the function body in which they are declared (delineated by
curly braces).
• Global variables and functions are visible to every Timeline and scope in your document.
For guidelines on using scope and variables, see Chapter 3, “Using scope,” on page 95 and
Chapter 3, “Avoiding _root,” on page 96.
Note: ActionScript 2.0 classes that you create support public, private, and static variable scopes. For
more information, see “Controlling member access” on page 256 and “Creating class members”
on page 263.
Timeline variables
Timeline variables are available to any script on that Timeline. To declare Timeline variables, use
the
var statement and initialize them in any frame in the Timeline; the variable will be available
to that frame and all following frames, as shown in the following example:
var x:Number = 15; //initialized in Frame 1, so it’s available to all frames
About variables45
Make sure to declare a Timeline variable before trying to access it in a script. For example, if you
put the code
var x = 10; in Frame 20, a script attached to any frame before Frame 20 cannot
access that variable.
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.
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.
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 41.
Global variables
Global variables and functions are visible to every Timeline and scope in your document. To
create a variable with global scope, use the
use the
var = syntax. For example, the following code creates the global variable myName:
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
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
46Chapter 2: ActionScript Basics
}
}
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. For more information, see “Flash
Player security features” on page 288.
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 in Flash Player
7 will be
var squared:Number = x*x;
trace(squared); // NaN in Flash Player 7; 0 in earlier versions
var x:Number = 6;
NaN or undefined, and your script might produce unintended results:
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
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
y remains 15, because y doesn’t look to x for its value; it contains the value
x is set to 15 and that value is copied into y. When x is changed to 30
About variables47
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 Output panel. Flash uses a zero-based index, which means that 0 is the first item in the array,
1 is the second, and so on.
In the following example,
zeroArray() by reference. The function zeroArray() accepts an Array object as a parameter
myArray contains an Array object, so it is passed to function
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
48Chapter 2: ActionScript Basics
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
This section describes general rules about common types of operators, operator precedence, and
operator associativity:
foo; foo and 3 are the operands:
+) operator adds the value of a numeric literal to the value of
• “Operator precedence and associativity” on page 49
• “Numeric operators” on page 51
• “Comparison operators” on page 52
• “String operators” on page 53
• “Logical operators” on page 53
• “Bitwise operators” on page 54
• “Equality operators” on page 54
• “Assignment operators” on page 55
• “Dot and array access operators” on page 56
For information on these operators, as well as special operators that don’t fall into these categories,
see Chapter 2, “ActionScript Language Reference” in Flash ActionScript Language Reference.
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.
Using operators to manipulate values in expressions49
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. Deprecated Flash 4 operators are listed in Appendix B, “Deprecated Flash 4
operators,” on page 311.For more information and guidelines on using operators and parentheses,
see Chapter 3, “Formatting code,” on page 76.
OperatorDescriptionAssociativity
Highest precedence
x++
x--
.
[ ]
( )
function ( )
++x
--x
-
~
!
new
delete
typeof
void
*
/
%
+
-
<<
>>
>>>
Post-incrementLeft to right
Post-decrementLeft to right
Object property accessLeft to right
Array elementLeft to right
ParenthesesLeft to right
Function callLeft to right
Pre-incrementRight to left
Pre-decrementRight to left
Unary negation, such as x = -1Left to right
Bitwise NOTRight to left
Logical NOTRight to left
Allocate objectRight to left
Deallocate objectRight to left
Type of objectRight to left
Returns undefined valueRight to left
MultiplyLeft to right
DivideLeft to right
ModuloLeft to right
Unary plusRight to left
Unary minusRight to left
Bitwise left shiftLeft to right
Bitwise right shiftLeft to right
Bitwise right shift (unsigned)Left to right
50Chapter 2: ActionScript Basics
OperatorDescriptionAssociativity
instanceof
Instance of (finds the class of which the object is an
Left to right
instance)
Requires Flash Player 6 or later
<
<=
>
>=
==
!=
&
^
|
&&
||
?:
=
*=, /=, %=, +=, -
=, &=, |=, ^=,
<<=, >>=, >>>=
,
Less thanLeft to right
Less than or equal toLeft to right
Greater thanLeft to right
Greater than or equal toLeft to right
EqualLeft to right
Not equalLeft to right
Bitwise ANDLeft to right
Bitwise XORLeft to right
Bitwise ORLeft to right
Logical ANDLeft to right
Logical ORLeft to right
ConditionalRight to left
AssignmentRight to left
Compound assignmentRight to left
CommaLeft 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)
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:
OperatorOperation performed
+
*
Addition
Multiplication
Using operators to manipulate values in expressions51
age is
OperatorOperation performed
/
%
-
++
--
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
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.
true or
The following table lists the ActionScript comparison operators:
OperatorOperation performed
<
>
52Chapter 2: ActionScript Basics
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).
true if the left operand alphabetically precedes the right operand (for
true if the left operand alphabetically follows the right operand (for example,
OperatorOperation performed
<=
>=
<>
!=
==Equality: Tests two expressions for equality. The result is true if the expressions are
===Strict equality: Tests two expressions for equality; the strict equality operator performs
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 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 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.
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:
Using operators to manipulate values in expressions53
if
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:
OperatorOperation performed
&&
||
!operandLogical 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.
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:
OperatorOperation performed
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Shift left
>>Shift right
>>>Shift right zero fill
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
54Chapter 2: ActionScript Basics
x.
The strict equality (===) operator is similar to the equality operator, with one important
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:
OperatorOperation 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.");
}
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:
OperatorOperation performed
=
+=
Assignment
Addition and assignment
Using operators to manipulate values in expressions55
OperatorOperation performed
-=
*=
%=
/=
<<=
>>=
>>>=
^=
|=
&=
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, including those of a movie clip.
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"];
Array access operator.
You can use the array access operator to dynamically set and retrieve
velocity in the movie clip
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();
56Chapter 2: ActionScript Basics
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.
You can check for matching
[] operators in your scripts; see “Checking syntax and punctuation”
on page 150.
Specifying an object’s path
To use an action to control a movie clip or loaded SWF file, you must specify its name and its
address, called a target path.
In ActionScript, you identify a movie clip by its instance name, either in the Property inspector or
dynamically, at runtime. For example, in the following statement, the
movie clip named
star._alpha = 50;
To give a movie clip on the Stage an instance name:
1.
Select the movie clip on the Stage.
2.
Enter an instance name in the Property inspector in the Instance Name text box.
star is set to 50% visibility:
_alpha property of the
Specifying an object’s path57
To dynamically create a movie clip:
• Use the MovieClip.attachMovie(), MovieClip.createEmptyMovieClip(), or
MovieClip.duplicateMovieClip() method. The following example uses the
attachMovie() method to dynamically create the purpleDot2_mc movie clip and place it on
top of the
greenBox_mc movie clip when the user rolls over the greenBox_mc clip, which is on
• Use _levelX, where X is the level number specified in the loadMovie() function that loaded
the SWF file.
For example, a SWF file loaded into level 5 has the target path
example, a SWF file is loaded into level 5 and its visibility is set to
//Load the SWF onto level 99.
loadMovieNum("contents.swf", 99);
//Set the visibility of level 99 to false.
loader_mc.onEnterFrame = function(){
_level99._visible = false;
};
To enter a SWF file’s target path:
_level5. In the following
false:
• In the Actions panel (Window > Development > Actions), click the Insert Target Path button
• Select a movie clip from the list that appears.
For more information on target paths, see “Using absolute and relative target paths” in Using Flash.
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.
Checking conditions
Statements that check whether a condition is
condition evaluates to
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
perform if previous conditions are false.
if (password == null || email == null) {
gotoAndStop("reject");
} else if (password == userID){
58Chapter 2: ActionScript Basics
if, else, else if, for, while, do while, for..in, or switch
true or false begin with the term if. If the
true, ActionScript executes the next statement. If the condition doesn’t
else if specifies alternative tests to
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
In the following example, the loop executes four times:
i = 4;
while (i>0) {
my_mc.duplicateMovieClip("newMC"+i, i, {_x:i*20, _y:i*20});
i--;
}
You can use the do..while statement to create the same kind of loop as a while loop. In a
do..while loop, the expression is evaluated at the bottom of the code block so the loop always
runs at least once.
This is shown in the following example:
i = 4;
do {
my_mc.duplicateMovieClip("newMC"+i, i, {_x:i*20, _y:i*20});
i--;
} while (i>0);
true. After each statement in the body is executed, the expression is evaluated again.
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
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});
}
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.
for action, the counter and
Using condition statements59
To loop through the children of a movie clip or an object:
• Use the for..in statement.
Children include other movie clips, 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—for example, over only
movie clip children. You can do this using
for (myname in my_object) {
if (typeof (my_object[myname]) == "anObject") {
trace("I have an object child named " + myname);
}
}
for..in with the typeof operator.
For more information on each action, see the individual entries in Flash ActionScript Language
Reference:
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 and are found in the Functions category of the Actions panel.
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, it must be in a frame that the playhead
has reached.
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 Flash ActionScript Language Reference.
60Chapter 2: ActionScript Basics
Creating functions
You can define functions to execute a series of statements on passed values. Your functions can
also return values. After a function is defined, it can be called from any Timeline, including the
Timeline of a loaded SWF file.
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 61
• “Passing parameters to a function” on page 62
• “Using variables in a function” on page 62
• “Returning values from a function” on page 62
• “Calling a user-defined function” on page 63
Defining a function
As with variables, functions are attached to the Timeline of the movie clip that defines them, and
you must use a target path to call them. As with variables, you can use the
declare a global function that is available to all Timelines and scopes without using a target path.
To define a global function, precede the function name with the identifier
the following example:
_global.myFunction = function (x:Number):Number {
return (x*2)+3;
}
To define a Timeline function, use the function statement followed by the name of the function,
any parameters to be passed to the function, and the ActionScript statements that indicate what
the function does.
The following example is a function named
function areaOfCircle(radius:Number):Number {
return Math.PI * radius * radius;
}
areaOfCircle with the parameter radius:
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.
_global identifier to
_global, as shown in
For information on strictly typing function return types and parameters, see “Strict data typing”
on page 41.
Creating functions61
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);
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.
62Chapter 2: ActionScript Basics
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;
}
Calling a user-defined function
You can use a target path to call a function in any Timeline from any Timeline, including from
the Timeline of a loaded SWF file. If a function was declared using the
_global identifier, you do
not need to use a target path to call it.
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
and stores the result in the variable
var temp:Number = this.mathLib.sqr(3);
sqr() in the movie clip mathLib on the main Timeline, passes the parameter 3 to it,
temp:
The following example uses an path to call the initialize() function that was defined on the
main Timeline and requires no parameters:
this.initialize();
The following example uses a relative path to call the list() function that was defined in the
functionsClip movie clip:
this._parent.functionsClip.list(6);
Creating functions63
64Chapter 2: ActionScript Basics
CHAPTER 3
Using Best Practices
It is important for Macromedia Flash designers and developers to build applications or
animations while being concerned about writing code and structuring applications in a way that
is beneficial either to themselves, or to the other people who might work on the project with
them. Because Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 are
powerful and complex programs, this complexity can sometimes create an uncertainty on how to
form a document, format code, or organize ActionScript in a project.
This chapter covers the following topics:
• “Working with FLA files” on page 66
• “General coding conventions” on page 69
• “ActionScript coding standards” on page 82
• “Using classes and ActionScript 2.0” on page 99
• “Behaviors conventions” on page 105
• “Screens conventions” on page 107
• “Video conventions” on page 110
• “Performance and Flash Player” on page 114
• “Guidelines for Flash applications” on page 121
• “Projects and version control guidelines” on page 127
• “Guidelines for accessibility in Flash” on page 129
• “Advertising with Flash” on page 136
Because it is common for more than one designer or developer to work on a single Flash project,
teams benefit when everyone follows a standard set of guidelines for using Flash, organizing FLA
files, and writing ActionScript code. The sections in this chapter outline the best practices for
using Flash and writing ActionScript. Following guidelines also encourages consistency for people
learning how to use Flash and write ActionScript. You should adopt best practices at all times,
whether you are a designer or developer, or working alone or as part of a team.
65
Therefore, it is particularly useful to follow guidelines in the following situations, and for the
following reasons:
When working on FLA documents Adopting consistent and efficient practices helps you speed
up your workflow. It is faster to develop using best practices, and easier to understand and
remember how you structured your document when you edit it further. Additionally, your code is
often more portable within the framework of a larger project, and easier to reuse.
When sharing FLA documents Other people editing the document can quickly find and
understand ActionScript, consistently modify code, and find and edit assets.
When working on projects Multiple authors can work on a project with fewer conflicts and
greater efficiency. Project or site administrators can manage and structure complex projects with
fewer conflicts or redundancies if you follow best practices.
When learning or teaching Flash Learning how to build Flash documents using best practices
reduces the need to relearn particular methodologies. If students learning Flash practice consistent
and better ways to structure code, they might learn the language more quickly and with less
frustration. If teachers and authors write using consistent practices and terminology, it is easier for
people in the community to learn how to use the program.
Consistent techniques and the following guidelines help those learning Flash or those working in
team environments. Consistent methods help you remember how you structured your document
when you work alone, particularly if you have not worked on the FLA file recently.
These are only a few of the reasons to learn and follow best practices. There are many other
reasons that you are sure to discover when you read these best practices and develop your own
good habits. Consider the following sections as a guideline when you are working with Flash; you
might choose to follow some or all of the recommendations. You can also modify the
recommendations to suit the way you work. The most important thing you can do when working
with Flash is to maintain consistency in how you create your documents, which helps you work
more efficiently. Many of the guidelines in this chapter help you develop a consistent way of
working with Flash and writing ActionScript.
Working with FLA files
Creating FLA files that are consistent makes it easier to work with Flash on a regular basis. It is
not uncommon to forget where you have placed particular elements, or what object instance code
is placed on. Therefore, follow these guidelines to help you avoid frustrating issues.
Organizing Timelines and the library
Frames and layers on a Timeline are two important parts of the Flash authoring environment.
These areas show you where assets are placed and determine how your document works. How a
Timeline and the library are set up and used affect the entire FLA file and its overall usability. The
following guidelines help you author content efficiently, and let other authors who use your FLA
documents have a greater understanding of how the document is structured:
• Give each layer an intuitive layer name, and place related assets together in the same location.
Avoid using the default layer names (such as Layer 1, Layer 2), because it can be confusing to
remember or locate assets when you are working on complex files.
66Chapter 3: Using Best Practices
• Clearly describe the purpose or content of each layer or folder when you name them in a FLA
file. This helps users to quickly understand where particular assets are found in layers or
folders. It is a good and common practice to name the layer that contains your ActionScript
actions and to use layer folders to organize similar layers.
• If applicable, place your layers that include ActionScript and a layer for frame labels at the top
of the layer stack in the Timeline. This makes it easy to locate the layers that include code and
labels.
• Add frame labels in a FLA file instead of using frame numbers in your ActionScript to
reference points on the Timeline. This is important and useful if you reference frames in your
ActionScript and those frames change later when you edit the Timeline. If you use frame labels
and move them on the Timeline, you do not have to change any references in your code.
• Lock your ActionScript layer immediately so that symbol instances or media assets are not
placed on that layer. Never put any instances or assets on a layer that includes ActionScript,
which can potentially cause conflicts between assets on the Stage and ActionScript that
references them.
• Lock layers that you are not using or do not want to modify.
• Use folders in the library to organize similar elements (such as symbols and media assets) in a
FLA file. If you name library folders consistently each time you create a file, it is much easier to
remember where you put assets. Commonly used folder names are Buttons, MovieClips,
Using scenes is similar to using several SWF files together to create a larger presentation. Each
scene has a Timeline. When the playhead reaches the final frame of a scene, the playhead
progresses to the next scene. When you publish a SWF file, the Timeline of each scene combines
into a single Timeline in the SWF file. After the SWF file compiles, it behaves as if you created
the FLA file using one scene. Because of this behavior, avoid using scenes for the following
reasons:
• Scenes can make documents confusing to edit, particularly in multiauthor environments.
Anyone using the FLA document might have to search several scenes within a FLA file to
locate code and assets. Consider loading content or using movie clips instead.
• Scenes often result in large SWF files. Using scenes encourages you to place more content in a
single FLA file and hence, larger documents to work with and larger SWF files.
• Scenes force users to progressively download the entire SWF file, even if they do not plan or
want to watch all of it. Your user progressively downloads the entire file, instead of loading the
assets they actually want to see or use. If you avoid scenes, the user can control what content
they download as they progress through your SWF file. This means that the user has more
control over how much content they download, which is better for bandwidth management.
One drawback is the requirement for managing a greater number of FLA documents.
• Scenes combined with ActionScript might produce unexpected results. Because each scene
Timeline is compressed onto a single Timeline, you might encounter errors involving your
ActionScript and scenes, which typically requires extra, complicated debugging.
Working with FLA files67
There are some situations where few of these disadvantages apply, such as when you create lengthy
animations, which is a good time to use scenes. If disadvantages apply to your document, consider
using screens to build an animation instead of using scenes. For more information on using
screens, see “Creating a new screen-based document (Flash Professional only)” in Using Flash.
Saving and version control
When you save your FLA files, it is important to consider using a naming scheme for your
documents. Most importantly, use a consistent naming scheme. This is particularly important if
you save multiple versions of a single project.
Use intuitive names for your files that are easy to read. Do not use spaces, capitalization, or special
characters. Only use letters, numbers, dashes, and underscores. If you save multiple versions of
the same file, devise a consistent numbering system such as site_menu01.swf, site_menu02.swf
and so on. Many designers and developers choose to use all lowercase characters in their naming
schemes. Many Flash designers and developers adopt a naming system that uses a noun-verb or
adjective-noun combination for naming files. Two examples of naming schemes are as follows:
class_planning.swf and my_project.swf. Avoid cryptic file names.
It is good practice to save new versions of a FLA file when you build an extensive project. The
following are different ways that you can save new versions of files:
• Select File > Save As, and save a new version of your document.
• Use version control software (such as SourceSafe, CVS, or Subversion) to control your Flash
documents.
Note: SourceSafe on Windows is the only supported version control software that integrates with the
Project panel. You can use other version control software packages with FLA documents, but not
necessarily in the Project panel. For more information on using Flash Projects and version control,
see “Using projects” on page 128.
Some problems might occur if you only work with one FLA file and do not save versions during
the process of creating the file. It is possible that files might bloat in size because of the history
that’s saved in the FLA file, or corrupt (as with any software you use) while you are working on
the file. If any of these unfortunate events occur, you will have other versions of your file to use if
you save multiple versions throughout your development.
You might also encounter problems when you create an application. Perhaps you made a series of
changes to the file, and you do not want to use these changes. Or, you might delete parts of the
file that you want to use later in your development. If you save multiple versions while
developing, you have an earlier version available if you need to revert.
There are several options that you can use to save a file: Save, Save As, and Save and Compact.
When you save a file, Flash does not analyze all the data before creating an optimized version of
the document. Instead, the changes you make to the document are appended to the end of the
FLA file’s data, which shortens the time it takes to save the document. When you select Save As
and type a new name for the file, Flash writes a new and optimized version of the file, which
results in a smaller file size. When you select Save and Compact, Flash creates a new optimized file
and deletes the original file.
68Chapter 3: Using Best Practices
Caution: When you select Save and Compact, you cannot undo any changes you made before you
saved the file. If you select Save when working with a document, you can undo prior to that save
point. Because Save and Compact deletes the earlier version of the file and replaces it with the
optimized version, you cannot undo earlier changes.
Remember to frequently use Save As and type a new file name for your document after every
milestone in your project if you are not using version control software to create backups of your
FLA file. If you encounter major problems while working on the document, you have an earlier
version to use instead of losing everything.
There are many software packages that allow users to use version control with their files, which
enables teams to work efficiently and reduce errors (such as overwriting files or working on old
versions of a document). Popular version control software programs include CVS, Subversion,
and SourceSafe. As with other documents, you can use these programs to organize the Flash
documents outside Flash.
General coding conventions
Typically, 80% of your development time is spent debugging, troubleshooting, and practicing
general maintenance, especially on larger projects. Even when you work on small projects, a
significant amount of time is usually spent analyzing and fixing code. When you are working on
large-scale projects, you might work with a team. The readability of your code is important for
your benefit and the benefit of your team members. When following conventions, you increase
readability, which increases workflow and helps find and fix any errors in your code, and all
programmers follow a standardized way of writing code, which improves the project in many
ways.
The following sections contain several suggestions and guidelines for general coding practices that
help improve your workflow and help teams working on a project. This section describes general
coding conventions that are true for many programming languages; “ActionScript coding
standards” on page 82 discusses conventions that are specific to ActionScript.
Note: Flash Player 7 closely follows the ECMA-262 Edition 4 proposal. It is useful to see this
proposal for information on how the language works. (See
www.mozilla.org/js/language/es4/index.html.)
General naming guidelines
This section covers naming guidelines for ActionScript and classes. The naming guidelines are
detrimental to creating logical code: the primary purpose is to improve readability of your
ActionScript. How you name a file can describe the item or process but not refer to its
implementation. Avoid using nondescriptive names for methods or variables. For example, if you
retrieve a piece of data that is the visitor’s username, you might use
less descriptive
getData(). This example expresses what is happening rather than how you
getUserName() instead of the
accomplish it. It is also a good idea to keep all names as short as possible.
Note: All variables must have unique names. Although names are case-sensitive in Flash MX 2004,
do not use the same name with a different case because this can be confusing to programmers
reading your code and cause problems in earlier versions of Flash that do not force case sensitivity.
General coding conventions69
Limit your use of abbreviations, but use them consistently. An abbreviation must clearly stand for
only one thing. For example, the abbreviation
sec might represent section and second. Make sure
you use it only for one term, and choose a different abbreviation for the other term.
Many developers concatenate words to create names. Use mixed casing when you concatenate
words to distinguish between each word for readability. For example, write myPelican rather thanmypelican.
Consider your own naming conventions that are easy to remember, and adapt them for situations
where you have common operations you are using. For more information on naming conventions
and guidelines, see the following topics:
• “Variable names” on page 70
• “Constants” on page 72
• “Functions” on page 72
• “Methods” on page 72
• “Loops” on page 72
• “Classes and objects” on page 73
• “Packages” on page 73
• “Interfaces” on page 74
• “Components and linkage” on page 74
Variable names
Variable names can only contain letters, numbers, and dollar signs (
names with numbers. Variables must be unique and they are case-sensitive in Flash Player 7 and
earlier. For example, avoid the following variable names:
my/warthog = true; //includes a backslash
my warthogs = false; //includes a space
5warthogs = 55; //begins with a number
Do not use words that are part of the ActionScript language as variable names. In particular, never
use keywords as instance names. For a list of keywords you should not use, see “Avoiding reserved
words” on page 75.
Note: Explicitly declare variables with var before you use them. Local variables are faster to access.
$). Do not begin variable
Avoid using variables that are parts of common programming constructs, even if Flash Player does
not include or support the constructs. Because ActionScript is ECMAScript-compliant,
application authors can use current ECMA specifications and proposals for information about
language structure. For a complete list of reserved or commonly used words, see “Avoiding
reserved words” on page 75.
For example, do not use the following keywords as variables:
Always strict data type your variables, which helps avoid errors in your code and trigger code
completion. For more information on strict typing and suffixes, see “Using code completion and
suffixes” on page 78. You should use suffixes with your variables because suffixes improve
ActionScript readability.
Try to keep variables as short as possible while retaining clarity. For more information on
processing and performance, see “Performance and Flash Player” on page 114. Some developers
use one character variables for temporary variables (such as
i, j, k, m, and n). Use single characters
only in certain cases, such as the following:
var font_array:Array = TextField.getFontList()
font_array.sort();
for (var i = 0; i<font_array.length; i++) {
trace(font_array[i]);
}
Start variables with a lowercase letter, and use mixed case for concatenated words. If you do not
use mixed case, then consistently use lowercase for all your variables. You can also use underscores
to separate concatenated words. Do not use a combination of these different naming conventions
in a single project.
Some developers use Hungarian notation to indicate the data type. Hungarian notation adds a
prefix before the variable name to identify what data type the variable is. This form of notation is
not recommended as a best practice. However, some developers use it as an alternative to adding
suffixes, so you should be aware of the practice. The following ActionScript uses Hungarian
notation to indicate the String data type:
var strMyName:String = "Rudy"; //indicates string
Use complementary pairs when you create a related set of variable names. For example, you might
use complementary pairs to indicate a minimum and maximum game score:
var minScore:Number = 10; //minimum score
var maxScore:Number = 500; //maximum score
The ActionScript editor and Script pane in the Actions panel have built-in support for code
completion. This means that Flash shows methods and properties for the current object when you
enter ActionScript code. You must name variables in a particular way or use specific commenting
techniques to see code completion menus. The following are the three ways to use code
completion:
• Use strict data typing, which is recommended if you are using ActionScript 2.0.
• Use suffixes, which is recommended if you are using ActionScript 1.
• Use comments, which is recommended only if you do not use suffixes or strict data typing.
For more information on code completion, see “Using code completion and suffixes” on page 78.
General coding conventions71
Constants
Variables should be lowercase or mixed-case letters; however, constants (variables that do not
change) should be uppercase. Separate words with underscores, as the following ActionScript
shows:
var BASE_URL:String = "http://www.macromedia.com"; //constant
var MAX_WIDTH:Number = 10; //constant
Write static constants in uppercase, and separate words with an underscore. Do not directly code
numerical constants unless the constant is
1, 0, or -1, which you might use in a for loop as a
counter value.
You can use constants for situations in which you need to refer to a property whose value never
changes. This helps you find typographical mistakes in your code that might not be found if you
used literals. It also lets you change the value in a single place.
Functions
Function names start with a lowercase letter. Describe what value is being returned when you
create function names. For example, if you are returning the name of a song title, you might name
the function
getCurrentSong().
Establish a standard for relating similar functions, because ActionScript does not permit
overloading. In the context of Object Oriented Programming (OOP), overloading refers to the
ability to make your functions behave differently depending on what data types are passed into it.
Methods
Name methods as verbs with mixed case for concatenated words, making sure that the first letter
is lowercase. For example, you might name methods in the following ways:
sing();
boogie();
singLoud();
danceFast();
You use verbs for most methods because they perform an operation on an object.
Loops
Loop indexes (such as a
(such as a
for loop or while loop) typically uses i, j, k, m, and n as control variables. Use these
for loop) have standardized naming conventions. A simple index loop
single-character variable names only for short loop indexes, or when performance optimization
and speed are critical.
72Chapter 3: Using Best Practices
Classes and objects
Class names are usually nouns or qualified nouns, beginning with an uppercase first letter. A
qualifier describes the noun or phrase. For example, instead of member, you might qualify the
noun using
NewMember or OldMember. Sometimes a class name is a compound word. Write class
names in mixed case beginning with an uppercase letter when the name includes concatenated
words. You do not have to pluralize the words you use in the class name, and, in most cases, it is
better to leave the words as qualified nouns.
Try to make the class name descriptive and simple, but most importantly, select a meaningful class
name. The name is descriptive of the class’s contents: do not be vague or misleading when you
name a class. Try to avoid acronyms and abbreviations unless they are more commonly used than
the long form (such as HTML), and remember that clear names are more important than short
names.
Do not use a class name in the properties of that class because it causes redundancy. For example,
it does not make sense to have
Cat.catWhiskers. Instead, Cat.whiskers is much better. Do not
use nouns that also might be interpreted as verbs, which might lead to confusion with methods,
states, or other application activities. Select meaningful, specific names rather than generic names.
See the following examples of class names for proper formatting:
class Widget;
class PlasticWidget;
class StreamingVideo;
It is a good practice to try and communicate the relationship a class has within a hierarchy when
you name it. This helps display its relationship within an application. For example, you might
have the
SteelWidget, and SmallWidget. For information on interfaces, see “Interfaces” on page 249.
For information on implementations, see
Widget interface, and the implementation of Widget might be PlasticWidget,
class in Flash ActionScript Language Reference.
You might have public and private member variables in a class. The class can contain variables
that you do not want users to set or access directly. Make these variables private and only allow
users to access the values using getter/setter methods. When naming member variables in your
class files, it is advisable and common practice to prefix the variable names with
m_. This helps
flag the variables as belonging to the class you’re creating, and generally makes the code more
readable.
Set most member variables to private unless there is a good reason for making them public. It is
much better from a design standpoint to make member variables private and allow access only to
those variables through a group of getter/setter functions. For more information on using private
and public member variables, see “Controlling member access” on page 256.
Packages
Put the prefix for a package name in all lowercase letters. Begin package names with
com.macromedia to maintain consistency when naming classes. The next parts of the package
mx or
name vary, depending on the particular naming scheme. For example, a convention might use
one of the following package names:
mx.containers.ScrollPane
General coding conventions73
// or
mx.containers.TextInput
This convention uses a prefix of mx.containers.
If you create your own packages, use a consistent naming convention, such as starting with
com.macromedia.PackageName. Or, use a convention of naming your packages
com.yourcompany.PackageName.
A clear and self-explanatory package name is important because it explains the package’s
responsibilities. For example, you might have a package named
drawing various kinds of geometric shapes using the Flash drawing API; its name would be
com.macromedia.Shapes.
Interfaces
Interface names have an uppercase first letter, the same as class names. Interface names are usually
adjectives, such as
uppercase letter and concatenated words with mixed case:
interface EmployeeRecords{}
Note: Some developers start interface names with an uppercase I to distinguish them from classes.
Components and linkage
Component names have an uppercase first letter, and any concatenated words are written in
mixed case. For example, the following default UI component set uses concatenated words and
mixed case:
Printable. The following interface name, EmployeeRecords, uses an initial
Shapes, which is responsible for
• CheckBox
• ComboBox
• DataGrid
• DateChooser
• DateField
• MenuBar
• NumericStepper
• ProgressBar
• RadioButton
• ScrollPane
• Te x t A re a
• Te x t In p u t
Components not using concatenated words begin with an uppercase letter.
If you develop custom components, use a naming convention to prevent naming collisions with
Macromedia components. The names of your components must be different from those of the
default set that is included with Flash. Adopting your own consistent naming convention
prevents naming conflicts.
74Chapter 3: Using Best Practices
For more information on Component conventions, see“Working with components in Flash
Player” on page 115.
Remember that the naming conventions in this section are guidelines. It is most important to use
a naming scheme that works well for you and use it consistently.
Avoiding reserved words
Avoid using reserved words as instance names in Flash. As a general rule, avoid using any word in
ActionScript as an instance or variable name. The following table lists reserved keywords in Flash
that cause errors in your scripts:
addandbreakcase
catchclasscontinuedefault
deletedodynamicelse
eqextendsfalsefinally
forfunctiongeget
gtififFrameLoadedimplements
importininstanceofinterface
intrinsicleitne
newnotnullon
onClipEventorprivatepublic
returnsetstaticsuper
switchtellTargetthisthrow
trytypeofvarvoid
whilewith
The following words are reserved for future use in Flash, from the ECMA-262 specification, and
ECMA-262 Edition 4 proposal. Avoid using these words because they might be used in future
editions of Flash.
asabstractBooleanbytes
charconstdebuggerdouble
enumexportfinalfloat
gotoislongnamespace
nativepackageprotectedshort
synchronizedthrowstransientuse
volatile
General coding conventions75
All class names, component class names, and interface names are also reserved words, as listed in
the following table:
Formatting ActionScript is essential to writing maintainable code. For example, it would be
extremely difficult to follow the logic of a FLA file that has no indenting or comments, or has
inconsistent formatting and naming conventions. By indenting blocks of code (such as loops and
if statements), the code is easy to read and debug. For more information on formatting and
white space, see “Spacing and readability” on page 81 and “Wrapping lines of code” on page 103.
For information on structuring ActionScript syntax, see “Writing syntax and statements”
on page 89.
76Chapter 3: Using Best Practices
For more information on formatting code, see the following topics:
• “Using comments in code” on page 77
• “Using code completion and suffixes” on page 78
• “Using recommended suffixes” on page 80
• “Spacing and readability” on page 81
Using comments in code
One of most important aspects of any project, whether it is a simple widget or a large scale
application, is documentation. Without comments, it is likely you will not know why code was
written or organized in a certain way. For this reason, it is important to thoroughly document
your code in key points of the application. For example, if you must write a certain workaround
for a complicated situation, document what you are doing and why. Whoever works with the
code in the future can understand what is happening and might not inadvertently break that
code.
Consistently use comments in your ActionScript, and describe what the code is doing. Using
comments is useful to help you remember coding decisions, and it is extremely helpful for anyone
else reading your code. Comments must clearly explain the intent of the code and not just
translate the code. If something is not readily obvious in the code, you should add comments to
it.
Avoid using cluttered comments, despite how popular they sometimes are to add. An example of
cluttered comments is a line of equal signs (=) or asterisks (*) used to create a block or separation
around your comments. Instead, use white space to separate your comments from the
ActionScript. If you format your ActionScript using the Auto Format tool, this removes the white
space. Remember to add it back in or use single comment lines (//) to maintain spacing; these
lines are easy to remove after you format your code.
Before you deploy your project, remove any superfluous comments from the code. If you find
that you have many comments in the ActionScript, consider whether you need to rewrite some of
the ActionScript. If you feel you must include many comments about how the code works, it is
usually a sign of inelegant ActionScript.
Note: Using comments is most important in ActionScript that is intended to teach an audience. For
example, add comments to your code if you are creating sample applications for the purpose of
teaching Flash, or if you are writing documentation on ActionScript.
Comments document the decisions you make in the code, answering both how and why. For
example, you might describe a workaround in comments. Therefore, the related code is easily
found for updating or fixing at a later date, by another developer, or if the issue is addressed in a
future version of Flash or Flash Player and the workaround is no longer necessary.
Use block comments for multiline comments, as the following example shows:
/*
The following ActionScript initializes variables used in the main and sub-
menu systems. Variables are used to track what options are clicked.
*/
General coding conventions77
Note: If you place the comment characters (/* and */) on separate lines at the beginning and end of
the comment, you can easily comment them out by placing double slash characters (//) in front of
them (for example, ///* and //*/). This lets you quickly and easily comment and uncomment your
code.
Use the following format for single-line comments:
// the following sets a local variable for age
var myAge:Number = 26;
The following single-line comment is formatted as a trailing comment, which is on the same line
as the ActionScript:
var myAge:Number = 26; //variable for my age
If you use the Auto Format feature with your code, trailing comments move to the next line. Add
these comments after you format your code, or you must modify their placement after using Auto
Format.
Sometimes you must distinguish important comments when writing code. The following
conventions demonstrate some of the common methodologies that programmers use.
When more code needs to be added to a section, you can use the following format:
// :TODO: comment
Use the following format when there is a known issue with your code or application, or there is
another problem. Note a bug’s ID or number, if possible. Adding a bug ID helps prevent
recurring problems and saves time.
// :BUG: [bug id] comment
When ActionScript needs further modifications because it is inelegant or does not follow best
practices, use the following format:
// :KLUDGE:
When ActionScript is intricately designed and interacts with other areas of an application, use the
following format to alert developers who might work on the code later:
// :TRICKY:
These practices help Flash users who learn from the commented source code. Another benefit of
using these methodologies is that you can easily locate bugs and unfinished items by using the
Find tool in the Actions panel.
Note: For readability, single-line comments (// ) are often used instead of block comments. This
increases the readability of the code for instructional purposes.
For information on using comments in classes, see “Using comments in classes” on page 102.
Using code completion and suffixes
Use strict data typing with your variables whenever possible because it helps you in the following
ways:
• Adds code completion functionality, which speeds up coding.
• Helps you avoid errors in your compiled SWF files.
78Chapter 3: Using Best Practices
To strict data type your variables, you must define the variable using the var keyword. In the
following example, when creating a LoadVars object, you would use strict data typing:
var params_lv:LoadVars = new LoadVars();
Strict data typing provides you with code completion, and ensures that the value of params_lv
contains a LoadVars object. It also ensures that the LoadVars object is not used to store numeric
or string data. Because strict typing relies on the
var keyword, you cannot add strict data typing
to global variables or parameters within an Object or array. For more information on strict typing
variables, see “Strict data typing” on page 41.
Note: Strict data typing does not slow down a SWF file. Type checking occurs at compile time (when
the SWF file is created), not at runtime.
Adding suffixes to your variable names serves the following important functions:
• It provides valuable code completion, which helps speed up the coding process.
• It makes your code readable, so you can immediately identify a variable’s data type.
For example, the following code creates an array that contains the names of each font installed on
the client computer. This code demonstrates the use of code suffixes (
(
:Array). Suffixes and strict typing let you use code completion, but strict typing ensures that a
variable maintains its data type. Suffixes improve the readability of your ActionScript; for
example, it is easier to understand what
font_array means, but font might not be as obvious in
the code. In the following example, if the code snippet tries to assign a string or numeric value to
font_array, an error is generated:
var font_array:Array = TextField.getFontList();
When you write instructional code, use suffixes to improve the code’s readability for students.
Suffixes help users learn ActionScript because they clarify each variable’s data type, which helps
explain the code’s structure.
_array) and strict typing
You can also generate code completion by using a specific comment technique. If you want to add
code completion for an object within your ActionScript, add the following comment to your
code:
// Object siteParams_obj;
Whenever you enter siteParams_obj. (with the dot [.]) into the Actions panel, the code
completion menu for your Object appears. Using comments to provide code completion is the
most obscure method; use it only as a last resort for code completion, such as when you need to
create backward-compatible files. The best and recommended methods for code completion and
readability are strict typing and suffixes, respectively.
To use code completion with components, you must import the component’s class, or provide the
full path to the ActionScript class name. Format your ActionScript in one of the following ways:
• You can specify its fully qualified class name, as the following example shows:
var myScrollPane:mx.containers.ScrollPane; //code completion works
• You can also use the import statement to reference the class, as the following example shows:
import mx.containers.ScrollPane;
var myScrollPane:ScrollPane; //code completion works
General coding conventions79
However, the following ActionScript throws an error and does not allow you to use code
completion:
var myScrollPane:ScrollPane; //no code completion, throws error
Using recommended suffixes
You can use the following suffixes to generate code completion in the Actions panel. They are
recommended because suffixes encourage consistency in code that might be shared among Flash
authors. Although suffixes are not necessary for code completion in ActionScript 2.0 documents,
using consistent suffixes helps other developers understand how your ActionScript works.
ObjectSuffix
Array_array
Button_btn
Camera_cam
Color_color
ContextMenu_cm
ContextMenuItem_cmi
Date_date
Error_err
LoadVars_lv
LocalConnection_lc
Microphone_mic
MovieClip_mc
MovieClipLoader_mcl
NetConnection_nc
NetStream_ns
PrintJob_pj
SharedObject_so
Sound_sound
String_str
TextField_txt
TextFormat_fmt
Video_video
80Chapter 3: Using Best Practices
Use the following suffixes with component instances. These suffixes do not generate code
completion in the Actions panel. However, using suffixes encourages consistency in ActionScript
that might be shared among developers.
ObjectSuffix
Accordion_acc
Alert_alert
Button_button
CheckBox_ch
ComboBox_cb
DataGrid_dg
DateChooser_dc
DateField_df
Label_label
List_list
Loader_ldr
Menu_menu
MenuBar_mb
NumericStepper_nstep
ProgressBar_pb
RadioButton_rb
ScrollPane_sp
TextArea_ta
TextInput_ti
Tree_tr
Window_win
Spacing and readability
Use spaces, line breaks, and tab indents to increase the readability of your code. Readability
increases by showing the code hierarchy, which you can emphasize with spacing. Spacing and
code readability are important because they make ActionScript easier to understand. This is
important for students learning ActionScript as well as experienced users working on complex
projects. Legibility is important when you are debugging ActionScript, because it is much easier
to spot errors when code is formatted correctly and properly spaced.
Put one blank line in between paragraphs of ActionScript Paragraphs of ActionScript are
groups of logically related code. By breaking the code into modules, it helps users reading the
ActionScript understand its logic. For more information on spacing in classes and statements, see
“Wrapping lines of code” on page 103.
General coding conventions81
Use line breaks to make complex statements easier to read You can format some
statements, such as conditional statements, in several ways. Sometimes, formatting statements
across several lines rather than a single line makes it easier to read. For more information on
properly formatting statements, see “Writing syntax and statements” on page 89.
Use consistent indentation in your code Indenting helps show the hierarchy of the code’s
structure. Use the same indentation throughout your ActionScript, and make sure that you align
the braces (
{}) properly. Aligned braces improve the readability of your code. If your ActionScript
syntax is correct, Flash automatically indents the code correctly when you press Enter (Windows)
or Return (Macintosh). You can also press the Auto Format button in the Actions panel to indent
your ActionScript if the syntax is correct.
Note: You can control autoindentation and indentation settings by selecting Edit > Preferences, and
then selecting the ActionScript tab.
ActionScript coding standards
One of the most important aspects about programming is consistency, whether it relates to
variable naming schemes, coding standards, or where you place your ActionScript code. Code
debugging and maintenance is dramatically simplified if the code is organized and adheres to
standards. Formatted code that follows an established set of guidelines is easier to maintain, and
easier for other developers to understand and modify.
For more information, see the following topics:
• “Organizing ActionScript in a document” on page 82
• “Writing ActionScript” on page 85
• “Using scope” on page 95
• “Using functions” on page 98
Organizing ActionScript in a document
It is important to understand where to put your ActionScript: Should it be in the FLA file, should
it be put on the server in an external AS file, or should it be a class written using ActionScript 2.0?
The first thing you must understand is how to structure your project. If you are building an
application, read “Building Flash Applications” on page 121.
A general guideline is to put all your code in as few places as possible, whether you put it inside a
FLA document or in external files. For information on choosing between ActionScript 1 or
ActionScript 2.0, see “Choosing between ActionScript 1 and ActionScript 2.0” on page 84.
Organizing your code helps you edit projects more efficiently, because you can avoid searching in
different places when you debug or modify the ActionScript. The following sections provide more
information about where to put your ActionScript.
82Chapter 3: Using Best Practices
Keeping actions together
Whenever possible, put your ActionScript in a single location. If you put code in a FLA file, put
ActionScript on the first or second frame on the Timeline, in a layer called actions that is the first
or second layer on the Timeline. Sometimes you might create two layers for ActionScript to
separate functions, which is an acceptable practice. Some Flash applications do not always put all
your code in a single place (in particular, when you use screens or behaviors). For more
information on organizing ActionScript in an application, see “Organizing files and storing code”
on page 125. For more information on design patterns, see “Using design patterns” on page 104
and “Using the MVC design pattern” on page 126.
Despite these rare exceptions, you can usually put all your code in the same location. The
following are the advantages of this process:
• Code is easy to find in a potentially complex source file.
• Code is easy to debug.
One of the most difficult parts of debugging a FLA file is finding all the code. After you find all
the code, you must figure out how it interacts with other pieces of code as well as the FLA file. If
you put all your code in a single frame, it is much easier to debug because it is centralized, and
these problems reduce in number. For information on attaching code to objects (and
decentralizing your code), see “Attaching code to objects” on page 83. For information on
behaviors and decentralized code, see “Using behaviors” on page 106.
Attaching code to objects
Avoid attaching ActionScript to objects in a FLA file, even in simple SWF files. Attaching code to
an object means that you select a movie clip, component, or button instance; open the Actions
panel; and add ActionScript using the
This practice is strongly discouraged for the following reasons:
on() or onClipEvent() handler functions.
• ActionScript that is attached to objects is difficult to locate, and the FLA files are difficult to
edit.
• ActionScript that is attached to objects is difficult to debug.
• ActionScript that is written on the Timeline or in classes is more elegant and easier to build
upon.
• ActionScript that is attached to objects encourages poor coding style.
• ActionScript that is attached to objects forces students and readers to learn different coding
styles, additional syntax, and a poor and limited coding style. This can be a frustrating
experience.
Some Flash users might say it is easier to learn ActionScript by attaching code to an object because
it might be easier to add simple code, or write about or teach ActionScript this way. A significant
problem exists because most people learning ActionScript need to know how to write the
equivalent code, which is not difficult. The contrast between two styles of coding can also be
confusing to people learning ActionScript, which is why consistency throughout the learning
process has advantages.
ActionScript coding standards83
Attaching ActionScript to a button called myButton_btn looks like the following ActionScript,
and should be avoided:
on (release) {
//do something
}
However, placing ActionScript with the same purpose on the Timeline looks like the following
code, which is encouraged:
For more information on ActionScript syntax, see “Writing syntax and statements” on page 89.
Note: Different practices apply when using behaviors and screens, which sometimes involves
attaching code to objects. For more information and guidelines, see “Comparing timeline code with
object code” on page 105 and “Organizing code for screens” on page 108.
Choosing between ActionScript 1 and ActionScript 2.0
When you start a new document or application in Flash, you must decide how to organize its
associated files. You might use classes in some projects, such as when you are building applications
or complex FLA files, but not all documents use classes. For example, many short examples in the
documentation do not use classes. Using classes to store functionality is not the easiest or best
solution for small applications or simple FLA files. In these cases, it is often more efficient to put
ActionScript inside the document. In this case, try to put all your code on the Timeline on as few
frames as possible, and avoid placing code on or in instances (such as buttons or movie clips) in a
FLA file.
When you build a small project, it is often more work and effort to use classes or external code
files to organize ActionScript instead of adding ActionScript within the FLA file. Sometimes it is
easier to keep all the ActionScript within the FLA file, rather than placing it within a class that
you import. This does not mean that you should necessarily use ActionScript 1. You might decide
to put your code inside the FLA document using ActionScript 2.0 with its strict data typing and
its new methods and properties. ActionScript 2.0 also offers a syntax that closely follows standards
in other programming languages. This makes the language easier and more valuable to learn. For
example, you will feel familiar with ActionScript if you have encountered another language that’s
based on the same structure and syntax standards. Or, you can apply this knowledge to other
languages you learn in the future. ActionScript 2.0 lets you use an object-oriented approach to
developing applications using an additional set of language elements, which can be advantageous
to your application development. For more information on the difference between ActionScript 1
and ActionScript 2.0, see “New object-oriented programming model” on page 21 and “Porting
existing scripts to Flash Player 7” on page 13.
There are cases in which you cannot choose which version of ActionScript to use. If you are
building a SWF file that targets an old version of Flash Player, such as a mobile device application,
you must use ActionScript 1, which is compatible.
84Chapter 3: Using Best Practices
Remember, regardless of the version of ActionScript, you should follow good practices. Many of
these practices, such as remaining consistent with case sensitivity, using code completion,
enhancing readability, avoiding keywords for instance names, and keeping a consistent naming
convention, apply to both versions.
If you plan to update your application in future versions of Flash, or make it larger and more
complex, you should use ActionScript 2.0 and classes, to make it easier to update and modify
your application.
ActionScript and Flash Player
If you compile a SWF file that contains ActionScript 2.0 with Publish Settings set to Flash Player
6 and ActionScript 1, code functions as long as it does not use ActionScript 2.0 classes. There is
no case sensitivity or strict data typing involved with the code. However, if you compile your
SWF file with Publish Settings set to Flash Player 7 and ActionScript 1, strict data typing and case
sensitivity are enforced.
ActionScript 2.0 is an improvement to the compiler in the Authoring environment, so you can
target earlier versions of Flash Player while working with ActionScript 2.0.
Writing ActionScript
ActionScript is a case-sensitive language. This means that variables can have the same name,
because slightly different capitalization is considered two separate instances, as the following
ActionScript shows:
var firstName:String = "Jimmy";
trace(firstname); //displays: undefined
In earlier versions of Flash (Flash MX and earlier), Flash would trace the string Jimmy in the
Output panel. Because Flash is case-sensitive,
firstName and firstname are two separate
variables. This is an important concept to understand. If your earlier FLA files have slightly
varying variable capitalization, you might experience unexpected results or broken functionality
when converting the file or application for Flash Player 7.
Note: You should not use two variables that differ only in case. If you are using them as separate
variables, change the instance name, not just the case.
Case sensitivity can have a large impact when working with a web service that uses its own rules
for variable naming and what case variables are in when they are returned to the SWF file from
the server. For example, if you use a Macromedia ColdFusion web service, property names from a
structure or object might be all uppercase, such as
FIRSTNAME. Unless you use the exact same case
in Flash, you are likely to experience unexpected results.
Try to keep ActionScript in a FLA file as generic as possible for the user interface. It is not ideal to
write ActionScript that depends on specific target paths. If the code needs to interact with
interface elements in a larger application, try using a model-view-controller based approach. For
more information, see “Using the MVC design pattern” on page 126.
ActionScript coding standards85
For more information on guidelines for writing ActionScript, see the following topics:
• “Adding initialization” on page 86
• “Using trace statements” on page 87
• “Using the super prefix” on page 87
• “Avoiding the with statement” on page 87
• “Using variables” on page 88
• “Writing syntax and statements” on page 89
• “Following general formatting guidelines” on page 95
Adding initialization
One of the easiest ways to initialize code using ActionScript 2.0 is to use classes. You can
encapsulate all your initialization for an instance within the class’s constructor function, or
abstract it into a separate method, which you would explicitly call after the variable has been
created, as the following code shows:
class Product {
function Product() {
var prod_xml:XML = new XML();
prod_xml.ignoreWhite = true;
prod_xml.onLoad = function(success:Boolean) {
if (success) {
trace("loaded");
} else {
trace("error loading XML");
}
};
prod_xml.load("products.xml");
}
}
The following code could be the first function call in the application, and the only one you make
for initialization. Frame 1 of a FLA document that is loading XML might use code that is similar
to the following ActionScript:
if (init == undefined) {
var prod_xml:XML = new XML();
prod_xml.ignoreWhite = true;
prod_xml.onLoad = function(success:Boolean) {
if (success) {
trace("loaded");
} else {
trace("error loading XML");
}
};
prod_xml.load("products.xml");
init = true;
}
86Chapter 3: Using Best Practices
Using trace statements
Use
trace statements in your documents to help you debug your code while authoring the FLA
file. For example, by using a
trace statement and for loop, you can see the values of variables in
the Output panel, such as strings, arrays, and objects, as the following example shows:
var day_array:Array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
var numOfDays:Number = day_array.length;
for (var i = 0; i<numOfDays; i++) {
trace(i+": "+day_array[i]);
}
This displays the following information in the Output panel:
0: sun
1: mon
2: tue
3: wed
4: thu
5: fri
6: sat
Using a trace statement is an efficient way to debug your ActionScript.
You can remove your
trace statements when you publish a SWF file, which makes minor
improvements to playback performance. Before publishing a SWF file, open Publish Settings and
select Omit Trace Actions on the Flash tab. For more information on using trace, see
trace() in
Flash ActionScript Language Reference.
Using the super prefix
If you refer to a method in the parent class, prefix the method with
super so that other developers
know from where the method is invoked. The following ActionScript demonstrates the use of
proper scoping using the
// readable
var pelican = super.bird;
var animal = super.super.bird;
super prefix:
The following ActionScript is not as readable. Avoid using the following syntax because it does
not reveal from where you invoke the method:
// not readable
var pelican = bird; // scoped to super.bird
var animal = super.super.bird;
Avoiding the with statement
One of the more confusing concepts for people learning ActionScript to understand is using the
with statement. Consider the following code that uses the with statement:
this.attachMovie("circle_mc", "circle1_mc", 1);
with (circle1_mc) {
There is an exception to this rule. When you are working with the drawing API to draw shapes,
you might have several similar calls to the same methods (such as
lineTo or curveTo) because of
the drawing API’s functionality. For example, when drawing a simple rectangle, you need four
separate calls to the
this.createEmptyMovieClip("rectangle_mc", 1);
with (rectangle_mc) {
If you wrote each lineTo or curveTo method with a fully qualified instance name, the code
would quickly become cluttered and difficult to read and debug.
Using variables
For the initial values for variables, assign a default value or allow the value of
following class example shows. This class sets the initial values of
empty strings:
class User {
private var m_username:String = "";
private var m_password:String = "";
function User(username:String, password:String) {
Delete variables or make variables null when you no longer need them. Setting variables to null
can still enhance performance. This process is commonly called garbage collection. Deleting
variables helps optimize memory use during runtime, because unneeded assets are removed from
the SWF file. It is better to delete variables than to set them to
null. For more information on
performance, see “Performance and Flash Player” on page 114.
For information on naming variables, see “Variable names” on page 70. For more information on
deleting objects, see
delete in Flash ActionScript Language Reference.
Writing syntax and statements
There are several ways to format or write a piece of ActionScript. Differences can exist in the way
you form the syntax, such as the way you form it across multiple lines in the Actions panel (for
example, where you put brackets (
{}) or parentheses [()]).
There are several general guidelines for writing ActionScript syntax. Place one statement per line
to increase the readability of your ActionScript. The following example shows correct and
incorrect statement usage:
There are several ways you can assign variables. Do not embed assignments, which is sometimes
used to improve performance in a SWF file at runtime. Despite the performance boost, your code
is much harder to read and debug. Consider the following ActionScript example:
var myNum = (a = b + c) + d;
If you assign variables as separate statements, it improves readability, as the following example
shows:
var a = b + c;
var myNum = a + d;
The following sections describe the preferred ways to format your syntax and statements in
ActionScript:
• “Writing conditional statements” on page 90
• “Writing compound statements” on page 91
• “Using the for statement” on page 92
• “Using while and do-while statements” on page 92
• “Using return statements” on page 93
• “Writing switch statements” on page 93
• “Using try-catch and try-catch-finally statements” on page 93
• “Using listener syntax” on page 94
ActionScript coding standards89
Writing conditional statements
Place conditions put on separate lines in if, else-if, and if-else statements. Your if
statements should use braces (
if-else, and else-if statements have the following formats:
//if statement
if (condition) {
//statements;
}
//if-else statement
if (condition) {
//statements;
} else {
//statements;
}
//else-if statement
if (condition) {
//statements;
} else if (condition) {
//statements;
} else {
//statements;
}
{}). You should format braces like the following examples. The if,
You can write a conditional statement that returns a Boolean value, as the following example
shows:
if (cart_array.length>0) {
return true;
} else {
return false;
}
However, compared with the previous code, the ActionScript in the following example is
preferable:
return (cart_array.length > 0);
The second snippet is shorter and has fewer expressions to evaluate. It’s easier to read and
understand.
The following condition checks if the variable
y is greater than zero, and returns the result of x/y
or a value of 0:
if (y>0) {
return x/y;
} else {
return 0;
}
The following example shows another way to write this code:
return ((y > 0) ? x/y : 0);
90Chapter 3: Using Best Practices
The shortened if statement syntax is known as the conditional operator (?:). It lets you convert
simple
if-else statements into a single line of code. In this case, the shortened syntax reduces
readability, and so it is not preferable. Do not use this syntax for complex code, because it is more
difficult to spot errors. For more information on using conditional operators, see “Writing
conditional statements” on page 90 and “Writing compound statements” on page 91.
When you write complex conditions, it is good form to use parentheses [()] to group conditions.
If you do not use parentheses, you (or others working with your ActionScript) might run into
operator precedence errors.
For example, the following code does not use parentheses around the condition:
if (fruit == apple && veggie == leek) {}
The following code uses good form by adding parentheses around conditions:
if ((fruit == apple) && (veggie == leek)) {}
If you prefer using conditional operators, place the leading condition (before the question mark
[
?]) inside parentheses. This helps improve the readability of your ActionScript. The following
code is an example of ActionScript with improved readability:
(y >= 5) ? y : -y;
Writing compound statements
Compound statements contain a list of statements within braces ({}). The statements within
these braces are indented from the compound statement, as the following ActionScript shows:
if (a == b) {
//this code is indented
trace("a == b");
}
In this example, the opening brace is placed at the end of the compound statement. The closing
brace begins a line, and aligns with the beginning of the compound statement.
Place braces around each statement when it is part of a control structure (
if-else or for), even if
it contains only a single statement. This good practice helps you avoid errors in your ActionScript
when you forget to add braces to your code. The following example shows code that is written
using poor form:
if (numUsers == 0)
trace("no users found.");
Although this code validates, it is considered poor form because it lacks braces around the
statements. In this case, if you add another statement after the
regardless of whether the
numUsers variable equals 0, which can lead to unexpected results. For
trace statement, it is executed
this reason, add braces so the code looks like the following example:
if (numUsers == 0) {
trace("no users found");
}
ActionScript coding standards91
Using the for statement
Write the for statement using the following format:
for (init; condition; update) {
// statements;
}
The following structure demonstrates the for statement:
Writ e do-while statements using the following format:
do {
//something
} while (condition);
The following is an example of a do-while statement:
var i:Number = 15;
do {
trace(i);
i++;
} while (i<5);
92Chapter 3: Using Best Practices
Using return statements
Do not use parentheses [()]with any return statements that have values. The only time you
should use parentheses with
return statements is when it makes the value more obvious, which is
shown in the third line of the following ActionScript:
return;
return myCar.paintColor();
// parentheses used to make the return value obvious
return ((paintColor)? paintColor: defaultColor);
Writing switch statements
All switch statements include a default case. The default case includes a break statement to
prevent a fall-through error if another case is added. For example, if the condition in the following
example evaluates to
statement. The
falls through, it does not have a
statement’s place, which you can see in the following example after
A, both the statements for case A and B execute, because case A lacks a break
default case should also be the last case in the switch statement. When a case
break statement, but includes a comment in the break
case A. Write switch
statements using the following format:
switch (condition) {
case A :
//statements
//falls through
case B :
//statements
break;
case Z :
//statements
break;
default :
//statements
break;
}
Using try-catch and try-catch-finally statements
Writ e try-catch and try-catch-finally statements using the following formats:
//try-catch
try {
//statements
} catch (myError) {
//statements
}
//try-catch-finally
try {
//statements
} catch (myError) {
//statements
} finally {
//statements
}
ActionScript coding standards93
Using listener syntax
There are several ways to write listeners for events in Flash MX 2004. Some popular techniques
are shown in the following code examples. The first example shows a properly formatted listener
syntax, which uses a Loader component to load content into a SWF file. The
starts when content loads, and the
var box_ldr:mx.controls.Loader;
var ldrListener:Object = new Object();
ldrListener.progress = function(evt:Object) {
The following example shows another recommended way of using a listener. In this example, you
define a function that is called when the user presses a Button component instance on the Stage:
var submit_button:mx.controls.Button;
submit_button.clickHandler = function(evt:Object) {
trace(evt.target._name);
}
By appending Handler to the event name (in this case, click), the event is caught, and you trace
an instance name when a user clicks the button.
A slight variation on the first example in this section is to use the
handleEvent method, but this
technique is slightly more cumbersome. It is not recommended, because you must use a series of
if..else statements or a switch statement to detect what event is caught.
var box_ldr:mx.controls.Loader;
var ldrListener:Object = new Object();
Adding spacing (or white space) to your syntax is recommended because it makes your
ActionScript easier to read. The following formatting points are recommended to help promote
readability in your ActionScript.
The following example includes a space after a keyword that is followed by parentheses [()]:
do {
//something
} while (condition);
You do not have to put a space between a method name and a following parentheses, as the
following example shows:
function checkLogin() {
//statements;
}
checkLogin();
If you follow these guidelines, it is easier to distinguish between method calls and keywords.
In a list of arguments, such as in the following example, include a space after commas:
function addItems(item1:Number, item2:Number):Number {
return (item1+item2);
}
var sum:Number = addItems(1, 3);
Separate all operators and their operands by spaces, as the following ActionScript shows:
var sum:Number = 7 + 3;
An exception to this guideline is the dot (.) operator. Unary operators such as increment (++) and
decrement (--) do not have spaces.
Using scope
Scope is the area where the variable is known and can be used in a SWF file, such as on the
timeline, globally across an application, or locally within a function. There are three kinds of
variables: local, timeline, and global. For information on these variables and scope, see “Scoping
and declaring variables” on page 45. ActionScript 2.0 classes also support public, private, and
static variable scopes.
It is important to understand the difference between the
scope is unique for each loaded SWF file. Use the
_global and _root scopes. The _root
_global identifier to create global objects,
classes, or variables. The global scope applies to all Timelines and scopes within SWF files. Use
relative addressing rather than references to
_root timelines, because it makes code reusable and
portable. See the following sections for the recommended way of scoping variables. For more
information on scope, see “Event handler scope” on page 174 and “Scope of the this keyword”
on page 176. For information on using the
super prefix, see “Using the super prefix” on page 87.
For more information on scope, see the following sections:
• “Avoiding _root” on page 96
• “Using _lockroot” on page 96
ActionScript coding standards95
• “Using the this keyword” on page 96
• “Using scope in classes” on page 97
Avoiding _root
There are several ways to target instances that let you avoid using
in this section. Avoid using
other SWF files to not work correctly. The
_root in ActionScript because it can cause SWF files that load into
_root identifier targets the base SWF file that is
loading, not the SWF file using relative addressing instead of
portability in SWF files that are loaded into another file, and, particularly, in components and
movie clips. You can help resolve problems using
_lockroot, but only use _lockroot when
necessary (such as when you are loading a SWF file but do not have access to the FLA file). For
more information on using
Use
this, this._parent, or _parent keywords rather than _root, depending on where your
_lockroot, see “Using _lockroot” on page 96.
ActionScript is located. The following example shows relative addressing:
myClip_mc.onRelease = function() {
trace(this._parent.myButton_btn._x);
};
All variables must be scoped, except for variables that are function parameters and local variables.
Scope variables relative to their current path whenever possible, using relative addressing, such as
the
this keyword. For more information on using the this keyword, see this in Flash
ActionScript Language Reference.
Using _lockroot
_root; these are discussed later
_root. This issue limits code
Flash MX 2004 introduced
with using
_root. Although this solves many problems with applications, consider _lockroot as
a workaround for problems caused by using
into a SWF file or a component instance, try applying
content. For example, if you have a movie clip called
_lockroot as a way to solve the scoping issues sometimes associated
_root. If you experience problems loading content
_lockroot to a movie clip that loads the
myClip_mc loading content, and it ceases
working after it is loaded, try using the following code (placed on the main Timeline):
this._lockroot = true;
For more information on using _lockroot, see MovieClip._lockroot in Flash ActionScript
Language Reference.
Using the this keyword
Whenever possible, use the
your code works without it. You can use the
this keyword as a prefix instead of omitting the keyword, even if
this keyword to learn when a method or property
belongs to a particular class. For example, for a function on the main Timeline, write
ActionScript using the following format:
For a class, you can write code in the following format:
class User {
private var m_username:String;
private var m_password:String;
function User(username:String, password:String) {
this.m_username = username;
this.m_password = password;
}
public function get username():String {
return this.m_username;
}
public function set username(username:String):Void {
this.m_username = username;
}
}
If you consistently add the this keyword in these situations, your ActionScript will be much
easier to read and understand.
Using scope in classes
When you port code to ActionScript 2.0 classes, you might have to change how you use the
keyword. For example, if you have a class method that uses a callback function (such as the
LoadVars class’s
onLoad method), it can be difficult to know if the this keyword refers to the
class or the LoadVars object. In this situation, it might be necessary to create a pointer to the
current class, as the following example shows:
class Product {
private var m_products_xml:XML;
// constructor
// targetXml_string - contains the path to an XML file
function Product(targetXml_string:String) {
/* Create a local reference to the current class.
Even if you are within the XML's onLoad event handler, you
can reference the current class instead of only the XML packet. */
var thisObj:Product = this;
// Create a local variable, which is used to load the XML file.
var prod_xml:XML = new XML();
prod_xml.ignoreWhite = true;
prod_xml.onLoad = function(success:Boolean) {
if (success) {
/* If the XML successfully loads and parses,
set the class's m_products_xml variable to the parsed
XML document and call the init function. */
thisObj.m_products_xml = this;
thisObj.init();
} else {
/* There was an error loading the XML file. */
trace("error loading XML");
}
};
this
ActionScript coding standards97
// Begin loading the XML document.
prod_xml.load(targetXml_string);
}
public function init():Void {
// Display the XML packet.
trace(this.m_products_xml);
}
}
Because you are trying to reference the private member variable within an onLoad handler, the
this keyword actually refers to the prod_xml instance and not the Product class, which you
might expect. For this reason, you must create a pointer to the local class file so that you can
directly reference the class from the
onLoad handler.
Using functions
Reuse blocks of code whenever possible. One way you can reuse code is by calling a function
multiple times, instead of creating different code each time. Functions can be generic pieces of
code, so you can use the same blocks of code for slightly different purposes in a SWF file. Reusing
code lets you create efficient applications and minimize the ActionScript that you must write,
which reduces development time. You can create functions in a class file or write ActionScript
that resides in a code-based component.
If you are using ActionScript 2.0, do not place functions on the Timeline. When using
ActionScript 2.0, place functions into class files whenever possible, as the following example
shows:
class Circle {
public function area(radius:Number):Number {
return (Math.PI*Math.pow(radius, 2));
}
public function perimeter(radius:Number):Number {
return (2 * Math.PI * radius);
}
public function diameter(radius:Number):Number {
return (radius * 2);
}
}
Use the following syntax when you create functions:
function myCircle(radius:Number):Number {
//...
}
Avoid using the following syntax, which is difficult to read:
myCircle = function(radius:Number):Number {
//...
}
The following example puts functions into a class file. This is a best practice when you choose to
use ActionScript 2.0, because it maximizes code reusability. When you want to reuse the
functions in other applications, you can import the existing class rather than rewrite the code
from scratch, or duplicate the functions in the new application.
98Chapter 3: Using Best Practices
class mx.site.Utils {
static function randomRange(min:Number, max:Number):Number {
if (min>max) {
var temp:Number = min;
min = max;
max = temp;
}
return (Math.floor(Math.random()*(max-min+1))+min);
}
static function arrayMin(num_array:Array):Number {
You create classes in separate ActionScript files that are imported into a SWF file when it is
compiled. To create a class file, the code you write can have a certain methodology and ordering,
which is discussed in the following sections.
Use the following basic ordering in your AS class files:
1.
Documentation comments
2.
Package and import statements
3.
Class and interface declarations
Using classes and ActionScript 2.099
The Flash MX 2004 object model does not support multiple inheritance; it supports only single
inheritance. Therefore, a class can come from a single parent class. This parent class can be either
a native Flash class or a user-defined class. Flash MX 2004 uses interfaces to provide additional
functionality, but only supports single inheritance. For information on interfaces, see “Interfaces”
on page 249. For information on implementing inheritance, see “Inheritance” on page 249. For
more information on Documentation comments, see “Using comments in classes” on page 102.
For information on import statements and class declarations, see “Creating a class file”
on page 251.
In ActionScript, the distinction between interface and object is only for the compile-time error
checking and language rule enforcement. An interface is not a class; however, this is not altogether
true in ActionScript at runtime. An interface is abstract, similar to the way it is in Java. However,
ActionScript interfaces do exist at runtime to allow type casting. An interface is not an object or a
class.
For more information, see the following topics:
• “Creating and organizing classes” on page 100
• “Programming classes” on page 102
• “Using prefixes in classes” on page 102
• “Using comments in classes” on page 102
• “Wrapping lines of code” on page 103
• “Using design patterns” on page 104
Creating and organizing classes
This section describes the structure of a class file. The following guidelines show how parts of a
class are ordered to increase efficiency and improve the readability in your code. For more
information on naming classes and parts of a class, see “General naming guidelines” on page 69.
The class file begins with documentation comments that include a general description of the
code, in addition to author information and version information.
Import statements follow the documentation comments. The first part of a package name is
written in lowercase letters and follows an established naming convention. For example, if you are
following the recommended naming guidelines, you might use the following statement:
import com.macromedia.Utils;
The next line of a class is a package statement, class declaration, or interface declaration, as the
following example shows:
class com.macromedia.users.UserClass{...}
Directly following the statement or declaration, include any necessary class or interface
implementation comments. Add information in this comment that is pertinent for the entire class
or interface.
Following the class or interface implementation comments, add all your static variables. Write the
public class variables first and follow them with private class variables.
100Chapter 3: Using Best Practices
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.