I have trouble understanding the scoping rules in Javascript.
In the example below, I would assume that scope url variable is private in the for-loop. And that the onloa
Javascript is not block-scoped, and thus requires a new function every time you want a new scope. See the answer by patrick dw.
This is why it is advantageous to use [].map(function(x){...})
or [].forEach(function(x){...})
which are in the javascript standard, since you'll need to define those functions anyway.
var imageArray = urlArray.map(function(url) {
var image = new Image();
image.src = url;
image.onload = function() {
alert(url);
};
return image;
});