1.12. Avoiding Conflicting Variables
Problem
You want to make sure that variables within a function do not interfere with variables in other functions or within the timeline in which the function is defined.
Solution
Use the var keyword to declare
local
variables.
Discussion
Generally, you should declare variables used within functions as
local variables. Local variables are known only
within the function. Therefore, they do not conflict with variables
of the same name in other functions or within the timelines in which
the functions are defined. To make a variable local, declare it with
the var keyword. Parameters are automatically
treated as local variables, so you do not need to include the
var keyword when declaring parameters for a
function.
function localVarsFunction (param1, param2) {
var myVar;
myVar = "Local variables are fun.";
}Or, more succinctly, you can write:
function localVarsFunction (param1, param2) {
var myVar = "Local variables are fun.";
}Variables declared without the var keyword are
implicitly scoped to the timeline on which they reside (note that
unlike some languages, ActionScript doesn’t require
you to declare a variable before assigning it a value for the first
time). In this case, myVar is a timeline
variable, not a local variable, even though it is declared
within a function:
function timelineVarsFunction ( ) {
myVar = "Timeline variables are fun but not usually a good choice in functions.";
}To declare a global variable, attach it as a property to the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access