JavaScript/Anonymous Functions

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Function Objects Index Next: Closures

[edit] Anonymous Functions

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessable after its initial creation.


Normal function declaration

function hello() {
 alert('world');
}
 
hello();

Lambda function declaration

var obj = new Object();
obj.hello = function() {
 alert('world');
};
 
obj.hello();


Anonymous function declaration

function() { alert('I am anonymous'); };
 
// This is kind of silly, because we can't even call the above function.
// That's why its anonymous.
// So what is the point?


The most common use for anonymous functions are as arguments to other functions, or as a closure.

setTimeout( 
 function() { alert('hello'); },
 1000);
 
// Our anonymous function is passed to setTimeout, which will execute the function in 1000 milliseconds.
 
(function() { alert('foo'); })();
 
// This is a common method of using an anonymous function as a closure which many javascript frameworks use.

Breakdown of the above statement:

  • the surrounding braces is a wrapper for the anonymous function
  • the trailing braces initiates a call to the function and can contain arguments
(function(message) { alert(message); })('foo');
// Another way to write the previous example and get the same result

arguments.callee

// prints the 100th Fibonacci number.
alert( (function(n){
           return n < 2
                ? n
                : arguments.callee(n - 2) + arguments.callee(n - 1);
       })(100) );

The arguments.callee local variable can be used within the function body and refers to the function by itself, which is necessary for recursive anonymous functions.

Note:
arguments.callee is deprecated in ECMAScript 5 Strict.

Previous: Function Objects Index Next: Closures
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export