HTML and CSS Reference
EXAMPLE 7.8 ( CONTINUED )
document.write( welcome("your Majesty") +
" May I take your coat? </br />");
A function definition is assigned to the variable named greetings . This time the
function will take an argument called visitor .
The return statement sends back to the caller the value of the message string as-
signed on the previous line .
Because the value of the variable greetings is a function definition, to activate the
function, we need to add parentheses to the variable name. Now the variable acts
as a function call.
We can assign the greetings variable to another variable. Now hello contains the
function definition. To call the function add parentheses to hello as hello() .
Now the variable welcome is assigned the name of the function called greetings . To
call the function, we add parentheses: welcome() .
The value of the variable, hello , is a function definition. To use the variable as a
function call, parentheses are added to its name, and any arguments passed within
the parentheses just as with any ordinary function call, e.g. hello(“Stranger”) .
The value of the variable, welcome , is a function definition. The function is called
by adding parentheses to the variable name, welcome (see Figure 7.12).
Figure 7.12 Variables used as functions
A closure is an a anonymous function defined within another function. When the outer
function exits, it returns a reference to the inner anonymous function, making it possible
to call the inner function via the reference. A closure means that the local variables can
remain accessible to the inner function even when it seems they should have gone out of
scope. The closure causes the variables to hang around until they are no longer needed.