JavaScript/Anonymous Functions

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Functions and Objects Index Next: Constructors and Prototypes

Anonymous Functions[edit]

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 accessible after its initial creation.


Normal function declaration

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


Anonymous function declaration

var anon = function() {
    alert('I am anonymous');
};
 
anon();


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 anonymous statements:

  • 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


An alternative representation of the above places the initiating braces to the surrounding braces and not the function itself, which causes confusion over why the surrounding braces are needed in the first place.

(function() {
    // ...
})();

Some have even resorted to giving the trailing braces technique derogatory names, in an effort to encourage people to move them back inside of the surrounding braces to where they initiate the function, instead of the surrounding braces.


arguments.callee

// returns the factorial of 10.
alert((function(n) {
    return !(n > 1)
    ? 1
    : arguments.callee(n - 1) * n;
})(10));

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.


Instead of using arguments.callee, which makes it impossible to achieve tail recursion (a future plan for JavaScript) and also results in a different this value - such issues are resolved by using a named function expression instead.

// returns the factorial of 10.
alert((function factorial(n) {
    return (n <= 1)
    ? 1
    : factorial(n - 1) * n;
})(10));
Previous: Functions and Objects Index Next: Constructors and Prototypes