HTML and CSS Reference
In-Depth Information
EXAMPLE
7.8 (
CONTINUED
)
7
document.write(
welcome("your Majesty")
+
" May I take your coat? </br />");
</script>
</big>
</body>
</html>
EXPLANATION
1
A function definition is assigned to the variable named
greetings
. This time the
function will take an argument called
visitor
.
2
The
return
statement sends back to the caller the value of the message string as-
signed on the previous line .
3
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.
4
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()
.
5
Now the variable
welcome
is assigned the name of the function called
greetings
. To
call the function, we add parentheses:
welcome()
.
6
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”)
.
7
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.