Functions as Objects
In 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.
Passing Functions to Functions
Perhaps 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:
function doCommand(command) {
command( ); // Executes the passed function
}
// Some examples:
doCommand(stop); // Pass the internal stop( ) function (stops the current movie)
doCommand(play); // Pass the internal play( ) function (plays the current movie)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 togotoAndPlay( )gp(25); // InvokegotoAndPlay( )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: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access