我试图按属性排序一些值,就像这样:

a = sorted(a, lambda x: x.modified, reverse=True)

我得到这个错误消息:

<lambda>() takes exactly 1 argument (2 given)

为什么?我该怎么解决呢?


这个问题最初是为Python 2.x编写的。在3。TypeError: sorted expected参数为1,got参数为2。

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

// 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(){})();但这不是:function(){}();?


我所知道的

在JavaScript中,像这样创建一个命名函数:

function twoPlusTwo(){
    alert(2 + 2);
}
twoPlusTwo();

你也可以创建一个匿名函数并将其赋值给一个变量:

var twoPlusTwo = function(){
    alert(2 + 2);
};
twoPlusTwo();

你可以通过创建一个匿名函数来封装一个代码块,然后将它包装在括号中并立即执行:

(function(){
    alert(2 + 2);
})();

这在创建模块化脚本时非常有用,可以避免由于潜在的冲突变量而使当前作用域或全局作用域混乱——就像Greasemonkey脚本、jQuery插件等情况一样。

现在,我明白为什么这是可行的了。括号将内容括起来,只公开结果(我相信有更好的方式来描述它),例如(2 + 2)=== 4。


我不明白

但我不明白为什么这不能同样有效:

function(){
    alert(2 + 2);
}();

你能给我解释一下吗?