Question

This question already has an answer here:

(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.

Was it helpful?

Solution

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).

OTHER TIPS

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/

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

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

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.

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
    }

})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top