在很多地方我看到这样的脚本:
(function () {
var hello = 'Hello World';
alert(hello);
})();
为什么不直接这样写,没有任何功能:
var hello = 'Hello World';
alert(hello);
在很多地方我看到这样的脚本:
(function () {
var hello = 'Hello World';
alert(hello);
})();
为什么不直接这样写,没有任何功能:
var hello = 'Hello World';
alert(hello);
我们使用自执行功能来管理变量范围。
变量的范围是定义它的程序区域。全局变量具有全局范围;它在您的 JavaScript 代码中随处定义。(即使在您的功能中)。另一方面,在函数中声明的变量仅在函数体内定义。它们是局部变量并且具有局部作用域。函数参数也算作局部变量,并且仅在函数体中定义。
var scope = "global";
function checkscope() {
alert(scope);
}
checkscope(); // global
如您所见,您可以访问scope
函数内部的变量,但是在函数体中,局部变量优先于同名的全局变量。如果你声明一个与全局变量同名的局部变量或函数参数,你实际上隐藏了全局变量。
var scope = "global";
function checkscope() {
var scope = "local";
alert(scope);
}
checkscope(); // local
alert(scope); // global
如您所见,函数内部的变量不会覆盖全局变量。由于这个特性,我们将代码放在自执行函数中,以防止在我们的代码变得越来越大时覆盖其他变量。
// thousand line of codes
// written a year ago
// now you want to add some peice of code
// and you don't know what you have done in the past
// just put the new code in the self executing function
// and don't worry about your variable names
(function () {
var i = 'I';
var can = 'CAN';
var define = 'DEFINE';
var variables = 'VARIABLES';
var without = 'WITHOUT';
var worries = 'WORRIES';
var statement = [i, can, define, variables, without, worries];
alert(statement.join(' '));
// I CAN DEFINE VARIABLES WITHOUT WORRIES
}());
IIFE (立即调用的函数表达式)避免创建全局变量hello
。
还有其他用途,但是对于您发布的示例代码,这就是原因。
除了保持全局命名空间干净之外,它们还有助于为可访问函数建立私有方法,同时仍公开一些属性以供以后使用 -
var counter = (function(){
var i = 0;
return {
get: function(){
return i;
},
set: function( val ){
i = val;
},
increment: function() {
return ++i;
}
};
}());
// 'counter' is an object with properties, which in this case happen to be
// methods.
counter.get(); // 0
counter.set( 3 );
counter.increment(); // 4
counter.increment(); // 5
可能有几个原因。
第一个是保护作用域,因为函数创建了一个新作用域。
另一个可以是绑定变量,例如
for (var i = 0; i < n; i++) {
element.onclick = (function(i){
return function(){
// do something with i
}
})(i);
}