0

Why does this outputs some weird thing?

And what do parenthesis around (function(i) { onImageLoad(i); }) do? It seems like they "materialize" the function but I would like to know the real term.

function startGame() {
    for (var i = 0; i < assets.length; i++) {
        frames.push(new Image());
        // correct
        //frames[i].onload = (function(i) { onImageLoad(i); })(i);
        // wrong
        frames[i].onload = function(i) { onImageLoad(i); };
        frames[i].src = assets[i];
    }
    setInterval(animate, frameRate);
}

onImageLoad = function(n) {
    console.log("image number", n, "loaded");
}

image number Event {clipboardData: undefined, cancelBubble: false, returnValue: true, srcElement: img, defaultPrevented: false…} loaded

Blue Skies
  • 2,935
  • 16
  • 19
ragezor
  • 360
  • 1
  • 4
  • 16
  • 1
    Please search for "creating handlers in a loop in JavaScript" or something similar. I'm certain you'll get all the info you need, and more. – Blue Skies Dec 05 '13 at 15:40
  • 4
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – p.s.w.g Dec 05 '13 at 15:41
  • @enhzflep: The parentheses don't create a closure. A function (every function) creates a closure. In the commented out code, the parentheses could actually be removed. – Blue Skies Dec 05 '13 at 15:42
  • @ragezor: The code that you have marked as `// correct` is not correct. It's invoking the handler immediately instead of assigning it. If it works, it's only because an `onload` handler wasn't needed in the first place. – Blue Skies Dec 05 '13 at 15:49
  • @BlueSkies I don't understand what handlers are. For me the code works and uncommented code prints weird output. I would like to know what is that is printing. How would you correct the "correct" code? – ragezor Dec 05 '13 at 15:59
  • The weird output is the `event` object. You just happened to name it `i`. The "correct" code works, because your code has no need to wait for the DOM to load. So the corrected version of that would simply be to do `onImageLoad(i);` without the `frames[i].onload = ` part, or the `function(i) { ... }:` part. – Blue Skies Dec 05 '13 at 16:07
  • How did the event object get there? – ragezor Dec 05 '13 at 16:13
  • It's passed to all event handlers when they're triggered by an event. – Blue Skies Dec 05 '13 at 20:26

0 Answers0