JavaScript closures and variable scope

前端 未结 2 1644
小蘑菇
小蘑菇 2020-12-21 04:12

I am having trouble with JS closures:

// arg: an array of strings. each string is a mentioned user.
// fills in the list of mentioned users. Click on a menti         


        
2条回答
  •  余生分开走
    2020-12-21 05:02

    The "i" reference inside the closure for the onclick handlers is trapping a live reference to "i". It gets updated for every loop, which affects all the closures created so far as well. When your while loop ends, "i" is just past the end of the mentions array, so mentions[i] == undefined for all of them.

    Do this:

    newAnchor.onclick = (function(idx) {
        return function () { loadUsernameInfo(mentions[idx]) };
    })(i);
    

    to force the "i" to lock into a value idx inside the closure.

提交回复
热议问题