Javascript closure - binding value instead of reference

*爱你&永不变心* 提交于 2019-12-21 20:59:12

问题


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.

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

回答1:


If you were to say:

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

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

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



回答2:


You pass the current value of i into the function helper. Inside that function the variable i, a (confusingly named) parameter to the function, is different from any other i. The closure returned thus binds to that particular i (really the [[scope]] which contains that i, but...).

Happy coding.




回答3:


This is a guess: i is a primitive, so it's always accessed by value, and not by reference.



来源:https://stackoverflow.com/questions/6728653/javascript-closure-binding-value-instead-of-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!