如何让这个匿名的Javascript函数引用正确的变量?

fen*_*ent 2 javascript scope anonymous-function

例:

var o = {};
for(var i = 0; i < 5; i++) {
  o[i] = function () {
      console.log(i);
  };
}

o[3]();
Run Code Online (Sandbox Code Playgroud)

当我调用o3时,它总是在控制台上显示5,即使我调用o0,o4或其中任何一个.它将始终显示5,因为这是我的最后一个值.如何在创建匿名函数时显示i的值?在o3中应该在控制台中显示3.

gbl*_*zex 5

你应该做:

var o = {};
for(var i = 0; i < 5; i++) {
  (function(i) { // <- self-executing anonymus function with a parameter i
    o[i] = function () {
        console.log(i); // <- i here will be the argument i, 
                        //    not the i from the loop
    };
  })(i); // <- pass i as an argument
}

o[3]();
Run Code Online (Sandbox Code Playgroud)

会发生什么是你创建一个叫做闭包的东西,以便保持i的状态.

Closure意味着内部函数保持对外部函数的引用,因此获得对其变量和参数的访问(即使在返回外部函数之后).

关闭的一个简单例子是:

function outer(arg) { 
  var variable = 5;
  arg = 2;
  function inner() {
    alert(variable);  // <- the inner function has access to the variables
    alert(arg);       //     and parameters of the outer function
  }
}
Run Code Online (Sandbox Code Playgroud)

自执行(自调用或立即)函数是在声明后立即调用的函数.

(function() {
  alert("executed immediately");
})();
Run Code Online (Sandbox Code Playgroud)

两者的结合以及只有函数在Javascript中具有作用域的事实,引导您使用上面提到的技术来创建具有新函数的作用域,该函数保持i的状态,否则由于闭包将由内部函数改变.