views:

468

answers:

5

I see people use "window.onload" all the time, but why? Isn't the "window" part completely superfluous?

A: 

window is an object with a property onload. Just setting the global variable onload doesn't mean anything.

Rusky
Global variables in JavaScript are actually properties on the window object. So, yes, setting the global variable `onload` does, oftentimes, mean something.
bdukes
Incorrect. `window` is the default scope of execution in a web browser, and all it's properties and methods act as the global variables. Example: `document` is a property of `window`, but most people use `document` on it's own, rather than `window.document`.
Jason Musgrove
Jason, this is exactly why I posted my question. If you can just call document in the window scope, why can't you just set onload in the window scope too?
sfjedi
+7  A: 

If you don't, then the onload method will be attributed to the current object, whatever that is (if any). So sometimes it may work, but writing window.onload is the most explicit, specific and safe way to do it.

Otávio Décio
Right. "onload" is not exclusively used for the window object. It can be used on images and other objects as well. Therefore window should always be specified.
DLH
JavaScript doesn't have an implied this, so it would only collide with another onload variable if it's a local variable or you are inside a "with ([some object with an onload property]) block.
Matthew Crumley
A: 

link text "The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading."

need to start working with the full DOM

andres descalzo
A: 
<script type="text/javascript">    
    if(window.addEventListener){
        window.addhandler= function(who, which, what){
         return who.addEventListener(which, what, false);
        }
    }
    else if(window.attachEvent){
        window.addhandler= function(who, which, what){
         return who.addEventListener('on'+which, what);
        }
    }        
    function somefunction(){
        alert('page loaded')  
    }    
    addhandler(window,'load',somefunction);    
</script>
kennebec