I have a variable in a loop inside a function:
function myHandler() {
for (var i = 0; i < items.length; i++) {
var currItem = items[i];
myObj.doSomething(function(data) {
console.log("ok");
console.log("My currItem id: " + currItem.id); // the last one of all in items
}, function(e) {
console.log("error");
console.log("My currItem id: " + currItem.id); // the last one of all in items
});
}
currItem.id
each time in console.log() is equal to the last of the items in items. Obviously. I've tried to fix this by this:
function myHandler() {
for (var i = 0; i < items.length; i++) {
var currItem = items[i];
var currItem = (function(i2) {
return items[i2];
})(i);
myObj.doSomething(function(data) {
console.log("ok");
console.log("My currItem id: " + currItem.id); // the last one of all in items
}, function(e) {
console.log("error");
console.log("My currItem id: " + currItem.id); // the last one of all in items
});
}
And still got no success. Why and how to fix it?