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() {
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.
<head><title>Anonymous Function</title>
<script type="text/javascript">
var greetings= function(){ // Anonymous function has no name
message="Greetings to you! "; // Function definition
return message;
<script type="text/javascript">
// greetings is a variable;
// its value is the function definition
document.write( text +"<br />");
text=greetings(); // Call function
document.write( text +"<br />");
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