views:

133

answers:

6
(function() {

  //do stuff

})();

EDIT: I originally thought this construct was called a closure - not that the effect that it caused results (potentially) in a closure - if variables are captured.

This is in no way to do with the behaviour of closures themselves - this I understand fully and was not what was being asked.

+1  A: 

I usually call it something like "the immediate invocation of an anonymous function."

Or, more simply, "function self-invocation."

Matt Ball
+2  A: 

It is an anonymous function (or more accurately a scoped anonymous function) that gets executed immediately.

The use of one is that any variables and functions that are declared in it are scoped to that function and are therefore hidden from any global context (so you gain encapsulation and information hiding).

Oded
Accepted as first answer posted.
James Westgate
A: 

It's called closure - or at least one of the cool stuffs you could do using closure :)

http://jameswilliamroberts.com/post/JavaScript-Patterns-e28093-Part-Deux.aspx

http://en.wikipedia.org/wiki/Closure_%28computer_science%29

Lukman
+2  A: 

it's an anonymous function but it's not a closure since you have no references to the outer scope

http://www.jibbering.com/faq/notes/closures/

Fabrizio Calderan
You don't know that.. He is "doing stuff" in there.
Thilo
no, he just has a comment ;). BTW if he has got some references on the outer scope then he has a closure
Fabrizio Calderan
+1  A: 

No, a closure is rather something along these lines:

function outer()
{
    var variables_local_to_outer;

    function inner()
    {
        // do stuff using variables_local_to_outer
    }

    return inner;
}

var closure = outer();

the closure retains a reference to the variables local to the function that returned it.

Edit: You can of course create a closure using anonymous functions:

var closure = (function(){

    var data_private_to_the_closure;

    return function() {
        // do stuff with data_private_to_the_closure
    }

})();
Edgar Bonet
+1  A: 

Kindof. It's doesn't really close around anything though, and it's called immediately, so it's really just an anonymous function.

Take this code:

function foo() {
    var a = 42;
    return function () {
        return a;
    }
}

var bar = foo();
var zab = bar();
alert(zab);

Here the function returned by foo() is a closure. It closes around the a variable. Even though a would apear to have long gone out of scope, invoking the closure by calling it still returns the value.

AHM