User Guide

About variables 45
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
String
and then try to create a String object using
new String(), the new object is undefined:
// 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
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