I saw this on twitter and I couldn’t explain it either. Defining a onload function in the following two manner works:
1) JSFiddle
<html>
<head>
<script>
onload = function(){
alert('this works');
};
</script>
</head>
<body>
</body>
</html>
2) JSFiddle
<html>
<head>
<script>
window.onload = function(){
alert('this works');
};
</script>
</head>
<body>
</body>
</html>
But when defined like the following, it doesn’t work even though it is assigned to window.onload
3) JSFiddle
<html>
<head>
<script>
function onload(){
alert('this doesnt work');
};
alert(window.onload); // this shows the definition of above function
</script>
</head>
<body>
</body>
</html>
What’s going on here?
The first two examples assign a function to the
window.onloadproperty (window.is implicit in the first example). Theonloadproperty actually belongs to the prototype ofwindow(conveniently calledWindow).The third variant declares a new local function with the same name, and that function shadows the property from the prototype. This means, when you ask for
window.onload, the engine finds the local version first, and gives up looking up the prototype chain. Soalert(window.onload);does alert your function source. However, for the event handler to work, it would have to be assigned to the prototype object’sonloadproperty.However, there is something odd going on: when you try to assign to a property that’s inherited from the
prototype, it shouldn’t work, and an “own” property should be created on the object, shadowing the one from the prototype (e.g. http://jsfiddle.net/ssBt9/). Butwindowbehaves differently (http://jsfiddle.net/asHP7/), and the behavior may even vary depending on the browser.