In the answers to this question, we read that function f() {} defines the name locally, while [var] f = function() {} defines it globally. That makes perfect sense to me, but there's some strange behavior that's different between the two declarations.
I made an HTML page with the script
onload = function() {
alert("hello");
}
and it worked as expected. When I changed it to
function onload() {
alert("hello");
}
nothing happened. (Firefox still fired the event, but WebKit, Opera, and Internet Explorer didn't, although frankly I've no idea which is correct.)
In both cases (in all browsers), I could verify that both window.onload and onload were set to the function. In both cases, the global object this is set to the window, and I no matter how I write the declaration, the window object is receiving the property just fine.
What's going on here? Why does one declaration work differently from the other? Is this a quirk of the JavaScript language, the DOM, or the interaction between the two?
windowrefers) may have host defined properties (such asonload) and an ECMAScript 3 implementation is free to implement the behaviour of such a property as it sees fit, including the internal[[Put]]method that is called when the value of the property is assigned.onload = function() {...};but not withvar onload = function() {...};var onload = ...andfunction onload() {...}forms.window.onload = function() {...};is not part of any current standard but pretty universally much supported across browsers, as is<body onload="...">. A combination ofwindow.addEventListenerandwindow.attachEventwill allow you to add multiple event handlers in all the major browsers, but beware of differences between the two.onload = function(){...}pattern — thinkweb2.com/projects/prototype/…