gdo*_*ica 7

它创建了closure一个隐藏变量的私有范围global object

// Somewhere...
var x = 2;

...
...
// Your code
var x = "foo" // you override the x defined before.

alert(x); // "foo"
Run Code Online (Sandbox Code Playgroud)

但是当你使用一个闭包时:

var x = 2;
// Doesn't change the global x
(function (){ var x = "foo";})();

alert(x); // 2
Run Code Online (Sandbox Code Playgroud)

关于语法,它只是一个自执行的函数,你声明它然后执行它.


Ufu*_*arı 6

它是一个自调用匿名函数或函数表达式.它可以防止您在全局范围内创建变量.它也立即调用该功能.

function someFunc() {
    // creates a global variable
}

var someFunc = function () {
    // creates a global variable
}

(function(){
    // creates an anonymous function and 
    // runs it without assigning it to a global variable
})();
Run Code Online (Sandbox Code Playgroud)