We write window.
when we want to be explicit about it. There are basically two cases when this is good form to use it:
- properties and methods of the
window
object - everything that is part of the Window
interface. The .onload
listener you've mentioned is an example of this, things like window.scrollY
, window.status
, window.parent
, window.open()
, window.focus()
, window.removeEventListener()
are others.
- creation of global properties. Assigning to
window.myGlobalVar
from any scope is a common JS idiom to create a global "variable". Admittedly, it is still better practise to explicitly declare it with var
.
While we could "optionally" omit the window.
part here, it's uncommon. Especially creation of implicitly global variables through assignment is despised, and usually seen as a mistake. So if you do it on purpose, you declare your intention by using window.
.
However, the first case is not always well-defined. We often do omit the window.
part when the property we want to use is essentially a static, global variable, and not necessarily related to the window
object even when it is formally specified on it. You seldom see anybody using document
, atob()
, Worker
, setTimeout()
or fetch()
with the window.
prefix, just as you don't use window.JSON.parse
or window.Array
for the built-in objects (although it would be valid).
For some other properties like navigator
, location
or alert()
it is not always clear, and those are used maybe fifty-fifty without or not.