Javascript closures - variable scope question

前端 未结 5 1899
借酒劲吻你
借酒劲吻你 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 13:48

    Its because at the time item.help is evaluated, the loop would have completed in its entirety. Instead, you can do this with a closure:

    for (var i = 0; i < helpText.length; i++) {
       document.getElementById(helpText[i].id).onfocus = function(item) {
               return function() {showHelp(item.help);};
             }(helpText[i]);
    }
    

    JavaScript doesn't have block scope but it does have function-scope. By creating a closure, we are capturing the reference to helpText[i] permanently.

提交回复
热议问题