Explaining odd behavior in javascript

I saw this on Twitter, and I couldn't explain it either. Defining the onload function in two ways:

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 if it is defined as the next one, it does not work, although window.onload assigned to it

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?

+3
source share
3 answers

The first two examples assign the function to the window.onload property ( window. Implicitly in the first example). The onload property actually belongs to the window prototype (conveniently called window ).

The third option declares a new local function with the same name, and this function obscures the prototype property. This means that when you request window.onload , the engine first finds the local version and refuses to search for the prototype circuit. Therefore alert(window.onload); warns your source function. However, for the event handler to work, it must be bound to the onload object object of the prototype object.

However, something strange happens: when you try to assign a property inherited from prototype , it should not work, and your own property should be created on the object, shading it from the prototype (for example, http://jsfiddle.net/ssBt9/ ). But window behaves differently ( http://jsfiddle.net/asHP7/ ), and the behavior may even change depending on the browser.

+9
source

This is because onload already declared and null before the script is executed.

This is similar to this code:

 var v=null; function v(){ console.log('hi'); }​​​​ console.log(v); // alerts null 

which is different from this:

 function v(){ console.log('hi'); }​​​​ console.log(v); // alerts the function 

When you declare such a function, the declaration and assignment logically rise to the "beginning" of the scope, so the assignment does not occur as soon as the onload function is null .

That's why it is different from

 window.onload=... 

which is not a declaration, but only an assignment that cannot be raised.

+3
source

In the first two cases, you define a member of the window called onload. In the third case, you define the function only, but are not a member of the current window.

0
source

All Articles