开发者

Is the following JavaScript construct called a Closure? [duplicate]

This question already has answers here: What is this practice called in JavaScript? (7 answers) Closed 8 years ago.
(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.

T开发者_如何学运维his 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
    }

})();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜