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

落爺英雄遲暮 提交于 2019-12-17 16:53:22

问题


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


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




回答2:


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/




回答3:


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

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




回答4:


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.




回答5:


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
    }

})();


来源:https://stackoverflow.com/questions/3872604/is-the-following-javascript-construct-called-a-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!