Home > Web Front-end > JS Tutorial > body text

How to Access Outside Variables in Loops from JavaScript Closures?

Patricia Arquette
Release: 2024-10-20 08:57:31
Original
814 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!