User Guide
28 Chapter 1: 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
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
Scoping and declaring variables
A variable’s scope refers to the area in which the variable is known and can be referenced. For
example, local variables are available within the function body in which they are declared
(delineated by curly braces [{}]), and global variables and functions are visible to every scope in
your document. Local and global variables are discussed later in this section. For more
information, see Developing Flex Applications.
Note: ActionScript classes that you create support public, private, and static variable scopes. For
more information, see “Controlling member access” on page 53 and “Creating class members”
on page 60.
Local variables
To declare local variables, use the
var statement inside the body of a function. A local variable
declared within a function block is defined within the scope of the function block and expires at
the end of the function block.
For example, the variables
i and j are often used as loop counters. In the following example, i is
used as a local variable; it exists only inside the function
initArray():
var myArray:Array = [ ];
function initArray(arrayLength:Number) {
var i:Number;
for( i = 0; i < arrayLength; i++ ) {
myArray[i] = i + 1;
}
}
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.