Javascript闭包 - 绑定值而不是引用

Dee*_*pan 3 javascript closures

以下示例取自"Javascript:The good parts"一书.作者说,辅助函数返回一个绑定到当前值的函数var i.

任何人都可以解释是什么让它绑定VALUE而不是REFERENCE var i,因为helper函数是一个add_the_handler函数闭包,应该只看到引用var i:

var add_the_handlers = function (nodes) {
   var helper = function (i) {
      return function (e) {
        alert(i);
      };
    };
    var i;
    for (i = 0; i < nodes.length; i += 1) {
       nodes[i].onclick = helper(i);
    }
};
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 5

如果你要说:

nodes[i].onclick = function(){ alert(i) };
Run Code Online (Sandbox Code Playgroud)

该函数不具有它自己的副本,i因为i未在函数范围内声明.

为了帮助您更好地了解这一点,我修改了您的上述代码:

var add_the_handlers = function (nodes) {
    var helper = function(t) {
      // t is in the scope of "helper"
      return function(e){
        // e is in the scope of this anonymous function
        // and is not used
        alert(t);
      };
    };

    // Variables declared here are in the scope of "add_the_handlers"
    var i;
    for (i = 0; i < nodes.length; i += 1) {
       nodes[i].onclick = helper(i);
    }
};
Run Code Online (Sandbox Code Playgroud)

在"现实世界"中,您经常会看到如上所示的代码缩写为:

var add_the_handlers = function(nodes){
    var i;
    for(i = 0; i < nodes.length; i++)
       nodes[i].onclick = (function(i){ return function(e){ alert(i); }; })(i);
};
Run Code Online (Sandbox Code Playgroud)