User Guide

About variables 47
}
}
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 variables value in Flash Player
7 will be
NaN or undefined, and your script might produce unintended results:
var squared:Number = x*x;
trace(squared); // NaN in Flash Player 7; 0 in earlier versions
var x:Number = 6;
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 variables 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,
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 doesnt look to x for its value; it contains the value
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