문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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
    }

})();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top