HTML and CSS Reference
In-Depth Information
EXPLANATION
2
In the function a variable called message is assigned a string. Rather than using an
alert box to send the message, it will be returned to the caller.
3
The return statement sends the message back to the caller of the function.
4
Notice that in this line we are displaying the value of the variable greetings . The
definition of the function is shown.
5
In this line the variable name is appended with parentheses, the () operator. This
operator causes JavaScript to call greetings as a function and return the result. In
the previous line, without the () operator, the value of the variable, a function def-
inition, is displayed (see Figure 7.11).
Figure 7.11 A variable with an anonymous function as its value
EXAMPLE 7.8
<html>
<head><title>Functions as Variable</title>
<script type="text/javascript">
1
var greetings=function (visitor){
// Function body is assigned to greetings
message="Greetings to you, " + visitor + "! ";
2
return message;
}
</script>
</head>
<body>
<big>
<script type="text/javascript">
3
var salutation=greetings("Elfie") ;
document.write(salutation + "<br />");
4
var hello = greetings;
// Function variable assigned to another variable
5
var welcome = greetings;
6
document.write( hello("Stranger") +"<br />");
// Call the function
Continues
Search WWH ::




Custom Search