Home >Web Front-end >JS Tutorial >How to Access Outside Variables in Loops from JavaScript Closures?
Access Outside Variable in Loop from JavaScript Closure
The problem arises when accessing variables declared within a loop, specifically when such variables are referenced later in an asynchronous callback. To exemplify, consider the following code snippet:
<code class="javascript">for (var i in this.items) { var item = this.items[i]; // ... }</code>
In this instance, the item variable will change with each loop iteration. When item is referenced later, it will hold the value from the last item in the array.
Solution: Using Closures
A solution to this issue involves employing closures, which create functions that return other functions. By using closures, the item variable can be scoped differently, as seen below:
<code class="javascript">for (var i in this.items) { var item = this.items[i]; // ... $("#showcasebutton_"+item.id).click( (function(item) { return function() { alert(item.id); self.switchto(item.id); }; })(item) ); }</code>
Alternative: jQuery's $.each() Helper
If jQuery is available, the $.each() helper can be used as a shorthand for simple for/each loops. It alleviates the need for closures due to the way scoping works in its function calls:
<code class="javascript">$.each(this.items,function(i, item) { // ... $("#showcasebutton_"+item.id).click(function() { alert(item.id); self.switchto(item.id); }); });</code>
The above is the detailed content of How to Access Outside Variables in Loops from JavaScript Closures?. For more information, please follow other related articles on the PHP Chinese website!