Javascript闭包 - 绑定值而不是引用 [英] Javascript closure - binding value instead of reference

查看:102
本文介绍了Javascript闭包 - 绑定值而不是引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The below example was taken from the book, "Javascript: The good parts". The author says that the helper function returns a function that binds to the current value of var i.

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

Can anyone explain what makes it to bind the VALUE instead of REFERENCE of var i, because helper function is a closure to add_the_handler function and should only see the reference of 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);
    }
};


推荐答案

如果你说:

nodes[i].onclick = function(){ alert(i) };

函数不会有自己的 i i 未在函数范围内声明。

The function would not have it's own copy of i because i is not declared within the scope of the function.

ve修改上面的代码:

To help you see this better I've modified your above code:

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);
    }
};

在现实世界中,你经常会看到类似上面的代码缩写为:

In the "real world" you'll often see code like the above shortened to look like this:

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);
};

这篇关于Javascript闭包 - 绑定值而不是引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆