Understanding JavaScript anonymous functions, variables, and scoping
<p>We're trying to understand variable scoping inside JavaScript anonymous functions.</p>

<p>This code only needs to work inside Webkit browsers since it's for a PhoneGap app.</p>

<p>Given the code block below, will the arguments to <strong>setTimeout</strong> always be the same for each item in <strong>all_packs</strong>, or will the changing value of <strong>pack_name</strong> (since it changes on each iteration of the jQuery loop) affect the arguments? In other words, each new row should be associated with a different item in <strong>all_packs</strong>. Is this the correct way to use anonymous functions, or will some rows end up referencing the same name?</p>

<p>We can't use <strong>this.name</strong> inside the <strong>tap</strong> anonymous function because <strong>this</strong> will no longer refer to the item inside <strong>all_packs</strong>. As a result, we first stashed the name inside <strong>pack_name</strong>.</p>

<p>Assume <strong>TAP_DELAY</strong> is a constant set elsewhere, <strong>start_work</strong> is a valid function, and <strong>all_packs</strong> is an array of objects.</p>

<pre><code>    // Load each pack
    $( all_packs ).each( function(index) {              
            // Set vars
            var pack_name = this.name;
            var row = $( '#templates .row' ).clone( true );

        // Append new row
        $( '#test' ).append( row );

            // Valid pack?
            if ( this.valid ) {             
                // Configure for tap
                row.on( 'tap', function() {
                                setTimeout( start_work, TAP_DELAY, pack_name );             
                });
            } else {
                            setTimeout( start_work, TAP_DELAY, this.name );
            }
        });
</code></pre>
