Blog Post RSS ?

Blogs » JavaScript & CSS » Is this a Safari bug?
 

Is this a Safari bug?

by Kevin Yank

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');
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. Implementing Event Latency in JavaScript Craig provides some useful JavaScript code to slow down event...
  2. Opera 10’s Y2K Bug: Browser Detection Goes Bad If you have fond memories of the Y2K bug, then...
  3. A First Look at Safari 4 Eighteen months after Safari 3, Apple has released version 4...
  4. How to Write a Cookie-less Session Library for JavaScript Craig provides the code for a stand-alone JavaScript session variable...
  5. An Introduction to JavaScript for Acrobat I’m always interested to see how JavaScript works on non-browser...

This post has 22 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...