JavaScript - - By Kevin Yank

Is this a Safari bug?

On my final editing pass of our upcoming book, The JavaScript Anthology, I’ve spotted what appears to be a previously unrecorded bug in Safari:

function preload(url) {
  var img = new Image();
  img.onload = function() {
    alert(this); // What is this?
  };
  img.src = url;
}
preload('chewbacca.jpg');

In well-behaved browsers like Firefox, Internet Explorer 6 and Opera 8.5, the above script loads the image and then displays some variation of “[object HTMLImageElement]”, which indicates that this refers to the image object for which the load event has just fired.

In Safari 1.3 and 2.0, however, the alert displays “[object window]”, because this refers instead to the window object within which the script is running.

Naughty Safari! Google didn’t seem to know about this bug when I asked it. Anyone seen this behaviour reported before?

Until this bug gets fixed, you should use a closure to refer to an image object from within its onload the event handler. That is, refer to a variable in the handler function’s enclosing scope.

function preload(url) {
  var img = new Image();
  img.onload = function() {
    alert(img);
  };
  img.src = url;
}
preload('chewbacca.jpg');
Sponsors