我读了一些关于闭包的帖子,到处都看到了这个,但是没有明确的解释它是如何工作的——每次我都被告知要使用它…:

// Create a new anonymous function, to use as a wrapper
(function(){
    // The variable that would, normally, be global
    var msg = "Thanks for visiting!";

    // Binding a new function to a global object
    window.onunload = function(){
        // Which uses the 'hidden' variable
        alert( msg );
    };
// Close off the anonymous function and execute it
})();

好的,我看到我们将创建一个新的匿名函数,然后执行它。所以在这之后,这段简单的代码应该工作了(它确实工作了):

(function (msg){alert(msg)})('SO');

我的问题是这里发生了什么魔法?当我写到:

(function (msg){alert(msg)})

然后将创建一个新的未命名函数,如function ""(msg)…

但为什么这行不通呢?

(function (msg){alert(msg)});
('SO');

为什么要在同一条线上?

你能给我指出一些帖子或者给我一个解释吗?


当前回答

匿名函数不是名称为“”的函数。它只是一个没有名字的函数。

与JavaScript中的其他值一样,函数不需要创建名称。不过,像绑定其他值一样,将它实际绑定到名称上要有用得多。

但是像任何其他值一样,您有时希望使用它时不将其绑定到名称。这就是自我调用模式。

这是一个函数和一个数字,没有界限,它们什么都不做,永远不能被使用:

function(){ alert("plop"); }
2;

所以我们必须将它们存储在一个变量中才能使用它们,就像任何其他值一样:

var f = function(){ alert("plop"); }
var n = 2;

你也可以使用synatic sugar将函数绑定到一个变量:

function f(){ alert("plop"); }
var n = 2;

但是如果不需要命名它们,并且会导致更多的混乱和更低的可读性,那么您可以立即使用它们。

(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5

在这里,我的函数和数字没有绑定到一个变量,但它们仍然可以使用。

这样说,看起来自调用函数没有真正的价值。但您必须记住,JavaScript范围分隔符是函数而不是块({})。

因此,自调用函数实际上与c++、c#或Java块具有相同的含义。这意味着在内部创建的变量不会“泄漏”到作用域之外。为了不污染全局作用域,这在JavaScript中非常有用。

其他回答

这就是JavaScript的工作原理。你可以声明一个命名函数:

function foo(msg){
   alert(msg);
}

叫它:

foo("Hi!");

或者,你可以声明一个匿名函数:

var foo = function (msg) {
    alert(msg);
}

称之为:

foo("Hi!");

或者,你可以永远不将函数绑定到一个名称:

(function(msg){
   alert(msg);
 })("Hi!");

函数也可以返回函数:

function make_foo() {
    return function(msg){ alert(msg) };
}

(make_foo())("Hi!");

make_foo函数体中任何用“var”定义的变量都将被make_foo返回的每个函数关闭,这是毫无意义的。这是一个闭包,这意味着一个函数对值所做的任何更改都将被另一个函数可见。

这让你可以封装信息,如果你想:

function make_greeter(msg){
    return function() { alert(msg) };
}

var hello = make_greeter("Hello!");

hello();

除了Java,几乎所有编程语言都是这样工作的。

这个答案与问题没有严格的联系,但是您可能有兴趣发现这种语法特性并不是函数特有的。例如,我们总是可以这样做:

alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"

与函数相关。因为它们是继承自Function的对象。原型,我们可以这样做:

Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo

你知道,我们甚至不需要用圆括号来包围函数来执行它们。不管怎样,只要我们试着把结果赋值给一个变量。

var x = function () {} (); // this function is executed but does nothing

function () {} (); // syntax error

对于函数,一旦声明了它们,就可以对它们调用new操作符并获得一个对象。以下是等价的:

var obj = new function () {
    this.foo = "bar";
};

var obj = {
    foo : "bar"
};

匿名函数不是名称为“”的函数。它只是一个没有名字的函数。

与JavaScript中的其他值一样,函数不需要创建名称。不过,像绑定其他值一样,将它实际绑定到名称上要有用得多。

但是像任何其他值一样,您有时希望使用它时不将其绑定到名称。这就是自我调用模式。

这是一个函数和一个数字,没有界限,它们什么都不做,永远不能被使用:

function(){ alert("plop"); }
2;

所以我们必须将它们存储在一个变量中才能使用它们,就像任何其他值一样:

var f = function(){ alert("plop"); }
var n = 2;

你也可以使用synatic sugar将函数绑定到一个变量:

function f(){ alert("plop"); }
var n = 2;

但是如果不需要命名它们,并且会导致更多的混乱和更低的可读性,那么您可以立即使用它们。

(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5

在这里,我的函数和数字没有绑定到一个变量,但它们仍然可以使用。

这样说,看起来自调用函数没有真正的价值。但您必须记住,JavaScript范围分隔符是函数而不是块({})。

因此,自调用函数实际上与c++、c#或Java块具有相同的含义。这意味着在内部创建的变量不会“泄漏”到作用域之外。为了不污染全局作用域,这在JavaScript中非常有用。

它不起作用的简单原因不是因为;表示匿名函数结束。这是因为在函数调用的末尾没有(),它就不是函数调用。也就是说,

function help() {return true;}

如果调用result = help();这是对函数的调用,返回true。

如果你拨打result = help;这不是电话。在这种分配中,帮助被视为要分配给结果的数据。

你所做的是通过添加分号来声明/实例化一个匿名函数,

(function (msg) { /* Code here */ });

然后尝试在另一个语句中调用它,只使用括号…显然,因为函数没有名称,但这将不起作用:

('SO');

解释器将第二行上的括号视为一个新的指令/语句,因此它不起作用,即使你这样做:

(function (msg){/*code here*/});('SO');

它仍然不能工作,但当您删除分号时,它可以工作,因为解释器会忽略空白和空格,并将完整的代码视为一条语句。

(function (msg){/*code here*/})        // This space is ignored by the interpreter
('SO');

Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".

(function (msg){alert(msg)})
('SO');

这是一种使用匿名函数作为闭包的常见方法,许多JavaScript框架都使用这种方法。

编译代码时自动调用此函数。

如果放置;在第一行,编译器将其视为两个不同的行。所以你不能得到和上面一样的结果。

这也可以写成:

(function (msg){alert(msg)}('SO'));

要了解更多细节,请参阅JavaScript/匿名函数。