Javascript closures - variable scope question

前端 未结 5 1908
借酒劲吻你
借酒劲吻你 2020-11-28 13:15

I\'m reading the Mozilla developer\'s site on closures, and I noticed in their example for common mistakes, they had this code:

Helpful

5条回答
  •  悲哀的现实
    2020-11-28 14:01

    I realize the original question is five years old... But you could also just bind a different/special scope to the callback function you assign to each element:

    // Function only exists once in memory
    function doOnFocus() {
       // ...but you make the assumption that it'll be called with
       //    the right "this" (context)
       var item = helpText[this.index];
       showHelp(item.help);
    };
    
    for (var i = 0; i < helpText.length; i++) {
       // Create the special context that the callback function
       // will be called with. This context will have an attr "i"
       // whose value is the current value of "i" in this loop in
       // each iteration
       var context = {index: i};
    
       document.getElementById(helpText[i].id).onfocus = doOnFocus.bind(context);
    }
    

    If you want a one-liner (or close to it):

    // Kind of messy...
    for (var i = 0; i < helpText.length; i++) {
       document.getElementById(helpText[i].id).onfocus = function(){
          showHelp(helpText[this.index].help);
       }.bind({index: i});
    }
    

    Or better yet, you can use EcmaScript 5.1's array.prototype.forEach, which fixes the scope problem for you.

    helpText.forEach(function(help){
       document.getElementById(help.id).onfocus = function(){
          showHelp(help);
       };
    });
    

提交回复
热议问题