O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Nested Functions

When a function definition occurs within a method or another function, it creates a nested function that is available for use within the containing method or function only. Conceptually, a function nested in a method or function defines a reusable subtask for the exclusive use of the containing method or function. The following code shows a generic example of a nested function, b( ), within an instance method, a( ). The nested function b( ) can be used within the method a( ) only; outside of a( ), b( ) is inaccessible.

// Define method a()
public function a () {
  // Invoke nested function b()
  b();

  // Define nested function b()
  function b () {
    // Function body would be inserted here
  }
}

In the preceding code, notice that the nested function can be invoked anywhere within the containing method, even before the nested function definition. Referring to a variable or function before it is defined is known as forward referencing. Further, note that access-control modifiers (public, internal, etc.) cannot be applied to nested functions.

The following code shows a more realistic example of a method containing a nested function. The method, getRandomPoint( ) returns a Point object representing a random point in a supplied rectangle. To produce the random point, the method uses a nested function, getRandomInteger( ), to calculate the random x- and y-coordinate. In getRandomInteger( ), notice the use of the built-in static methods Math.random( ) and Math.floor( ). The Math.random( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required