
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Methods
|
101
In order to avoid confusion, you should avoid giving properties and local variables
the same name. See “Managing parameter/property name conflicts,” earlier in the
chapter, for related details.
Nesting Functions in Methods
ActionScript supports nested functions, which means that functions can be declared
within methods or even within other functions. The following code creates a
method, Box.getArea( ), that contains a nested function, multiply( ). Inside getArea( ),
the nested function can be invoked as usual. However, like a local variable, a nested
function is accessible only to its parent function (the function in which it is
declared). Code outside the parent function cannot execute the nested function:
class Box {
private var width:Number;
private var height:Number;
public function getArea ( ):Number {
return multiply(width, height);
// Here's the nested function definition.
// Only the getArea( ) method can invoke it. Other methods cannot.
function multiply (a:Number, b:Number):Number {
return a * b;
}
}
}
Nested functions are used commonly when assigning callback functions to
setInterval( ) or to objects that support event handler properties, such as MovieClip,
Sound, and XML (callback functions are merely functions triggered when a particular
event has occurred). ...