Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is declaring a function at global scope not equivalent to assigning a function to a global-scope binding?

I saw this on Twitter and I couldn't explain it either. Defining a onload function in the following two manner works:

onload = function(){
  console.log('this works');
};

window.onload = function(){
  console.log('this works');
};

But when defined like the following, it doesn't work even though it is assigned to window.onload

function onload(){
  console.log('this does not work');
};
console.log(window.onload); // this shows the definition of above function

What's going on here?

like image 393
Ashfame Avatar asked Oct 29 '25 18:10

Ashfame


1 Answers

THIS IS WRONG, PLEASE REFER TO THE NEWEST ANSWER BELOW

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.

like image 183
bfavaretto Avatar answered Nov 01 '25 08:11

bfavaretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!