Access index of multiple callbacks instantiated in for loop
<p>I am invoking an API function - which takes a callback - multiple times in a for-loop.  My callback needs to do something index-specific.  I can't change the willCallBack function (it is part of the API) and I want to avoid creating global variables.</p>

<p>The following snippet illustrates the problem.  The first for-loop was my first attempt, but it returns i==4 for all callbacks.  The second for-loop works - but it is ugly and feels 'hackish'</p>

<p>What is a cleaner way of getting the value of 'i' into the callback function definition?</p>

<pre><code>var result = '', result2 = '';

// doesn't work; i == 4 for all
for(var i=0; i&lt;4; i++) {
    willCallBack(function(msg) {
        result += msg + i + '\n';
    });
}

// works, but kinda ugly
for(var i=0; i&lt;4; i++) {
    willCallBack(function(i) {
        return function(msg) {
            result2 += msg + i + '\n';
        };
    }(i));
}

// part of API, cant change
function willCallBack(cb) {
    window.setTimeout(cb, 500, "can't change me");
}

// show the results
window.setTimeout(function(){
        alert(result + '\n\n' + result2)
    }, 1000);
</code></pre>
