JavaScript closures and variable scope

前端 未结 2 1623
小蘑菇
小蘑菇 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 04:52

    Your iterator i is stored as a reference, not as a value and so, as it is changed outside the closure, all the references to it are changing.

    try this

    function fillInMentioned(mentions) { 
        var mentionList = document.getElementById("mention-list"); 
        mentionList.innerHTML = ""; 
        for (var i = 0; i < mentions.length; i++) { 
            var newAnchor = document.createElement("a"); 
    
            // Set the index as a property of the object 
            newAnchor.idx = i;
            newAnchor.onclick = function () { 
                // Now use the property of the current object
                loadUsernameInfo(mentions[this.idx]) 
            }; 
    
            // give this anchor the necessary content 
            newAnchor.innerHTML = mentions[i]; 
    
            var newListItem = document.createElement("li"); 
            newListItem.appendChild(newAnchor); 
            mentionList.appendChild(newListItem); 
        } 
        document.getElementById("mentions").setAttribute("class", "");  
    } 
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题