Advanced Function Scope Issues

This section describes another advanced topic that was too esoteric for our initial discussion about function scope. Let’s revisit it here now that we’ve learned about movie clips, function scope, and objects.

We learned in Chapter 9 that a function’s scope chain is normally determined relative to the function’s declaration statement. There is, however, a subtle extension to this rule. When a function from one timeline is assigned to a variable in a different movie clip’s timeline, that assignment also affects the function’s scope chain. If the original function is invoked directly, its scope chain includes its original timeline, but if the function is invoked through the variable, its scope chain includes the variable’s timeline.

For example, suppose we create a function called transformClip( ) that rotates and scales the current clip. We set the amount to rotate and scale the clip in the variable’s rotateAmount and widthAmount:

var rotateAmount = 45;
var widthAmount = 50;

function transformClip ( ) {
	_rotation = rotateAmount;
	_xscale = widthAmount;
}

// Invoke the function
transformClip( );

Next we assign transformClip to a variable, tc, in a clip called rect:

rect.tc = transformClip;

When we invoke transformClip through rect.tc, as follows, nothing happens:

rect.tc( );

Why? The function stored in tc has a scope chain that includes rect, not our original function’s timeline, so rotateAmount and widthAmount are not found. But when we add rotateAmount and ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.