9.11. Functions as ObjectsIn ActionScript, functions are technically a special type of built-in object. Let's see what that means and how it affects what you can do with functions. 9.11.1. Passing Functions to FunctionsPerhaps surprisingly, we can use any function as an argument to another function like this: function1(function2); Note that if there are no parentheses following function2, the interpreter doesn't execute function2( ) but instead just passes its "object reference" as an argument to function1( ). That is, function1( ) receives function2 itself, not the return value of function2( ). Because objects are passed by reference, we can pass a function identifier to another function and it will arrive unscathed. The passed function can be executed like this:
Because functions are a type of object, we may treat them like any other data. In the following example, we assign the internal gotoAndPlay function to the variable gp, which gives us a shorter way to refer to the function: gp = gotoAndPlay; // Create a shortcut reference to gotoAndPlay( ) gp(25); // Invoke gotoAndPlay( ) using our reference In addition to passing and storing functions as objects, we can exploit the "objectness" of functions by attaching properties to them, like this:
Function properties offer the benefits of local variables without expiring between function invocations. This is useful when a function needs to be invoked with a unique identifier. Here, for example, is a generic function that duplicates a movie clip and gives the duplicated clip a unique name and level:
Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|