为什么使用自执行功能?

27 javascript function

在很多地方我看到这样的脚本:

(function () {
    var hello = 'Hello World';
    alert(hello);
})();
Run Code Online (Sandbox Code Playgroud)

为什么不这样写,没有任何功能:

var hello = 'Hello World';
alert(hello);
Run Code Online (Sandbox Code Playgroud)

小智 33

我们使用自执行功能来管理变量范围.

变量的范围是程序中定义它的区域.全局变量具有全局范围; 它在JavaScript代码中随处定义.(即使在你的功能中).另一方面,函数内声明的变量仅在函数体内定义.它们是局部变量并具有局部范围.函数参数也算作局部变量,并且仅在函数体内定义.

var scope = "global";
function checkscope() {
    alert(scope);
}

checkscope(); // global
Run Code Online (Sandbox Code Playgroud)

如您所见,您可以访问scope函数内部的变量,但是,在函数体内,局部变量优先于具有相同名称的全局变量.如果声明一个与全局变量同名的局部变量或函数参数,则可以有效地隐藏全局变量.

var scope = "global";
function checkscope() {
    var scope = "local";
    alert(scope);
}

checkscope(); // local
alert(scope); // global
Run Code Online (Sandbox Code Playgroud)

如您所见,函数内部的变量不会覆盖全局变量.由于这个特性,我们把代码放在自执行函数中,以防止覆盖其他变量,当我们的代码变得越来越大.

// 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
}());
Run Code Online (Sandbox Code Playgroud)


Ted*_*opp 13

所述IIFE(立即调用函数表达式)可以避免创建一个全局变量hello.

还有其他用途,但对于您发布的示例代码,这就是原因.


Rob*_*ben 6

除了保持全局命名空间干净之外,它们还可用于为可访问函数建立私有方法,同时仍然暴露一些属性供以后使用 -

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
Run Code Online (Sandbox Code Playgroud)