JavaScript/Anonymous Functions

From Wikibooks, the open-content textbooks collection

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 declartion

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 is 1000 millaseconds.
 
(function() { alert('foo'); })();
 
// This is a common method of using an anonymous function as a closure which many javascript frameworks use.


Paragraph about arguments.callee

Previous: Function Objects Index Next: Closures