We write window. when we want to be explicit. There are basically two cases where this is a good form to use:
- The properties and methods of the
window object are all that are part of the window interface . The .onload that you mentioned is an example of this, other things like window.scrollY , window.status , window.parent , window.open() , window.focus() , window.removeEventListener() . - creation of global properties. Assigning
window.myGlobalVar from any scope is a common JS idiom for creating a global "variable". Admittedly, it's even better to use to explicitly declare it with var .
Although we could βoptionallyβ omit the window. part here window. , it's unusual. In particular, the creation of implicitly global variables through assignment is despised and is usually regarded as a mistake. Therefore, if you do this on purpose, you declare your intention using window. .
However, the first case is not always clearly defined. We often omit the window. part window. when the property that we want to use is essentially a static global variable and is not necessarily associated with the window object, even if it is formally indicated on it. You rarely see anyone using the document , atob() , Worker , setTimeout() or fetch() window. prefix window. just like you are not using window.JSON.parse or window.Array for inline objects (although that would be true).
For some other properties, such as navigator , location or alert() , this is not always clear, and they are used, maybe fifty fifty without or not.
Bergi source share