For example, suppose we define a variable,
firstName, on the timeline of a movie clip,
clipA. We also declare a function,
getName( ), on clipA. Inside
getName( ), we refer to the variable
firstName in a trace( )
statement:
firstName = "Christine";
function getName ( ) {
trace(firstName);
}
getName( );
When we invoke getName( ), the interpreter must
find the value of firstName. There is no variable
called firstName in the local scope of
getName( ), so the interpreter checks the
timeline of clipA for the variable
firstName. There, the interpreter finds
firstName and displays its value,
"Christine".
Our trace( ) statement is able to refer to a
timeline variable from the body of our getName(
) function because getName( ) does
not, itself, define a parameter or variable called
firstName. Now consider what happens when we add a
parameter called firstName to the
getName( ) function:
firstName = "Christine";
function getName (firstName) {
trace(firstName);
}
getName("Kathy");
This time, when we invoke getName( ), we assign
the value "Kathy" to the parameter
firstName. When the interpreter executes the
trace( ) statement, it searches the local scope
where it finds the firstName parameter and its
value "Kathy". So the output of the function this time is
"Kathy" not "Christine". Even though the
timeline variable firstName exists, the
function's local variable called firstName
takes precedence.
function dynamicGoto( ) {
// Deliberately go outside the function's local scope
_root.myClip.gotoAndPlay(_root.myClip.targetFrame);
}
Note that a function's scope chain is determined relative to
the function declaration statement, not any
function invocation statement. That is, the code
in a function's body is scoped to the movie clip that bears the
function declaration, not the movie clip that bears the statement
that invokes the function.
Here's an example showing a misguided use of the scope chain:
// CODE ON MAIN MOVIE TIMELINE
// This function's scope chain includes the main movie
function rotate(degrees) {
_rotation += degrees;
}
If we attempt to rotate clipA using
_root.rotate, it rotates the entire main movie,
not just clipA:
// CODE ON clipA's TIMELINE
_root.rotate(30); // Oops! This rotates the entire movie!
In this situation we can fix our problem by passing the clip to be
rotated as an argument to the rotate( )
function:
function rotate (theClip, degrees) {
theClip._rotation += degrees;
}
// Invoke rotate( ) with a reference to clipA
_root.rotate(clipA, 30);