About variables 43
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
_global identifier before the variable name, and do
not use the
var = syntax. For example, the following code creates the global variable myName:
var _global.myName = "George"; // syntax error
_global.myName = "George";
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:
_global.counter = 100;
counter++;
trace(counter); // displays 101
function count(){
for( var counter = 0; counter <= 10 ; counter++ ) {
trace(counter); // displays 0 through 10
}
}
count();
counter++;
trace(counter); // displays 102
Using variables in a program
You must declare a variable in a script before you can use it in an expression. If you use an
undeclared variable, as shown in the following example, the variable’s value will be
NaN or
undefined, and your script might produce unintended results:
var squared = x*x;
trace(squared); // NaN
var x = 6;
In the following example, the statement declaring the variable x must come first so that squared
can be replaced with a value:
var x = 6;
var squared = x*x;
trace(squared); // 36
Similar behavior occurs when you pass an undefined variable to a method or function:
getURL(myWebSite); // no action
var myWebSite = "http://www.macromedia.com";
var myWebSite = "http://www.macromedia.com";
getURL(myWebSite); // browser displays www.macromedia.com
You can change the value of a variable many times in a script. The type of data that the variable
contains affects how and when the variable changes. Primitive data types, such as strings and
numbers, are passed by value. This means that the actual content of the variable is passed to
the variable.
In the following example,
x is set to 15 and that value is copied into y. When x is changed to 30
in line 3, the value of
y remains 15 because y doesn’t look to x for its value; it contains the value of
x that it received in line 2.
var x = 15;
var y = x;
var x = 30;