Running Functions
We
run
a function like a wizard invokes a spell, by proclaiming the
function’s name, followed by the
function call operator, ( )
, introduced in Chapter 5:
funcName
( )
(You can almost detect the faint odor of smoldering mandrake root in the air.)
The parentheses may contain any parameters defined by the function.
If the function defines no parameters, the parentheses are left
empty. Let’s try invoking our sayHi( )
function, which has no parameters, to get the hang of basic function
invocation.
Here, again, is our sayHi( )
function
declaration:
function sayHi ( ) { trace("Hi there!"); }
And here’s our sayHi( )
function
invocation:
sayHi( );
When that line is executed, sayHi( )
is invoked,
so its function body runs, causing “Hi there!” to appear
in the Output window.
You can see that typing sayHi( ); is more
convenient than typing the whole trace( )
statement, and the function name sayHi
is a more
meaningful description of what our code does. Using thoughtful
function names makes our code more readable, almost like human
sentences.
Before we continue, notice the semicolon at the end of the function call:
sayHi( );
We add the semicolon because a function call is a complete statement, and good form dictates that all statements should end in a semicolon.
Believe it or not, we’ve just learned the basics of creating and invoking functions. Not too shabby. Functions keep your code centralized and easier to maintain, especially when you need to perform the same operation repeatedly ...
Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.