Is this a Safari bug?

Share this article

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');
Kevin YankKevin Yank
View Author

Kevin Yank is an accomplished web developer, speaker, trainer and author of Build Your Own Database Driven Website Using PHP & MySQL and Co-Author of Simply JavaScript and Everything You Know About CSS is Wrong! Kevin loves to share his wealth of knowledge and it didn't stop at books, he's also the course instructor to 3 online courses in web development. Currently Kevin is the Director of Front End Engineering at Culture Amp.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week