Explaining odd behavior in javascript

javascript

Solution

The first two examples assign a function to the `window.onload` property (`window.` is implicit in the first example). The `onload` property actually belongs to the prototype of `window` (conveniently called `Window`).

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. So `alert(window.onload);` does alert your function source. However, for the event handler to work, it would have to be assigned to the prototype object's `onload` property.

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/). But `window` behaves differently (http://jsfiddle.net/asHP7/), and the behavior may even vary depending on the browser.

Problem

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?

Original source