HTML and CSS Reference
In-Depth Information
7.1.3 Anonymous Functions as Variables
A function definition can be assigned directly to a variable. The variable is like any other
variable except that its value is a function definition and this variable is used as a refer-
ence to the function. The () is a JavaScript operator, indicating that a function is to be
called. Pay close attention to the use of the () operator in the next example and how it
affects the outcome of the function variable. Later we will use these anonymous func-
tions with event methods as follows:
window.onload = function() {
alert("Welcome");
}
When the Web page has finished loading, the onload event is triggered and JavaScript
will execute the anonymous function statements, in this case an alert box.
EXAMPLE 7.7
<html>
<head><title>Anonymous Function</title>
<script type="text/javascript">
1
var greetings= function(){ // Anonymous function has no name
2
message="Greetings to you! "; // Function definition
3
return message;
}
</script>
</head>
<body>
<big>
<script type="text/javascript">
4
text=greetings;
// greetings is a variable;
// its value is the function definition
document.write( text +"<br />");
5
text=greetings(); // Call function
document.write( text +"<br />");
</script>
</big>
</body>
</html>
EXPLANATION
1
A function without a name, called an anonymous function, is given its definition
between the curly braces. The definition of the function is assigned to the variable
greetings . We can say then that greetings is the name of a variable whose value is a
function definition and that greetings is a reference to the function.
 
 
Search WWH ::




Custom Search