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');


Category: javascript Time: 2006-01-31 Views: 1

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.100 (s). 12 q(s)