User Guide

104 ActionScript Language and Syntax
Function scope
A functions scope determines not only where in a program that function can be called, but
also what definitions the function can access. The same scope rules that apply to variable
identifiers apply to function identifiers. A function declared in the global scope is available
throughout your code. For example, ActionScript 3.0 contains global functions, such as
isNaN() and parseInt(), that are available anywhere in your code. A nested function—a
function declared within another function—can be used anywhere in the function in which it
was declared.
The scope chain
Any time a function begins execution, a number of objects and properties are created. First, a
special object called an activation object is created that stores the parameters and any local
variables or functions declared in the function body. You cannot access the activation object
directly because it is an internal mechanism. Second, a scope chain is created that contains an
ordered list of objects that Flash Player checks for identifier declarations. Every function that
executes has a scope chain that is stored in an internal property. For a nested function, the
scope chain starts with its own activation object, followed by its parent functions activation
object. The chain continues in this manner until it reaches the global object. The global
object is created when an ActionScript program begins, and contains all global variables and
functions.
Function closures
A function closure is an object that contains a snapshot of a function and its lexical
environment. A functions lexical environment includes all the variables, properties, methods,
and objects in the functions scope chain, along with their values. Function closures are
created any time a function is executed apart from an object or a class. The fact that function
closures retain the scope in which they were defined creates interesting results when a function
is passed as an argument or a return value into a different scope.
For example, the following code creates two functions:
foo(), which returns a nested
function named
rectArea() that calculates the area of a rectangle, and bar(), which calls
foo() and stores the returned function closure in a variable named myProduct. Even though
the
bar() function defines its own local variable x (with a value of 2), when the function
closure
myProduct() is called, it retains the variable x (with a value of 40) defined in function
foo(). The bar() function therefore returns the value 160 instead of 8.
function foo():Function
{
var x:int = 40;