Accessing Outside Variable in Loop from Javascript Closure
In JavaScript, when using a closure, the variable within the loop is referenced by a pointer. This means that when the loop is complete, the last value of the variable is used, leading to discrepancies in functionality.
To address this problem, a technique called a closure can be employed. A closure is essentially a function that returns a function. By scoping the variable differently using a closure, we can ensure that each iteration of the loop refers to its own distinct value of the variable.
Consider the following code:
for (var i in this.items) { var item = this.items[i]; $("#showcasenav").append("<li id=\"showcasebutton_"+item.id+"\"><img src=\"/images/showcase/icon-"+item.id+".png\" /></li>"); $("#showcasebutton_"+item.id).click( // create an anonymous function that will scope "item" (function(item) { // that returns our function return function() { alert(item.id); self.switchto(item.id); }; })(item) // immediately call it with "item" ); }
In this modified code, an anonymous function is created within each iteration of the loop that takes the current value of the item as an argument. This ensures that each click handler has its own distinct instance of the item variable.
Alternatively, jQuery's $.each() helper function can be used to simplify the code and eliminate the need for a closure:
$.each(this.items,function(i, item) { $("#showcasenav").append("<li id=\"showcasebutton_"+item.id+"\"><img src=\"/images/showcase/icon-"+item.id+".png\" /></li>"); $("#showcasebutton_"+item.id).click(function() { alert(item.id); self.switchto(item.id); }); });
By using a closure or jQuery's $.each(), we can ensure that each iteration of the loop has access to its own unique value of the variable, resolving the issue of accessing outside variables outside of the loop.
The above is the detailed content of When Looping in JavaScript Closures, How to Maintain Access to Unique Variable Values?. For more information, please follow other related articles on the PHP Chinese website!