Accessing Outside Variable in Loop from JavaScript Closure
In JavaScript, when iterating over an array using a for-loop, it's common to encounter an issue where the value of a variable inside the loop is always the same as the last iteration. This arises due to variable scope and closures.
To resolve this issue, a technique called closures can be employed. A closure is a function that returns a function, which captures the variable scope of the parent function.
Consider the following example:
<code class="javascript">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(function() { alert(item.id); self.switchto(item.id); }); }</code>
In this code, the variable item changes with each iteration of the loop. When the click handler is invoked, it uses the last value of item.
To solve this, we can use a closure to capture the scope of the loop variable:
<code class="javascript">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" ); }</code>
Here, we wrap the click handler function in another function that captures the scope of item during the loop iteration. When the click handler is invoked, it uses the correct value of item.
An alternative approach is to use jQuery's $.each() function, which automatically scoops the loop variable, eliminating the need for a closure:
<code class="javascript">$.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); }); });</code>
The above is the detailed content of How to Access an Outside Variable within a JavaScript Closure Loop?. For more information, please follow other related articles on the PHP Chinese website!