我读了一些关于闭包的帖子,到处都能看到这一点,但没有明确的解释它是如何工作的-每次我只是被告知使用它.:
// 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)})
然后将创建一个新的未命名函数,如函数""(Msg).
但为什么这不管用呢?
(function (msg){alert(msg)});
('SO');
为什么要排在同一条线上呢?
你能给我指出一些帖子或给我一个解释吗?