Some properties and methods are consistently prefixed with window.
while others are not.
For example, document
and setTimeout()
are almost never used with window.
prefix. On the other hand, window.location
and window.open()
are very often used with the prefix.
I know that they essentially refer to the same thing, and that without window.
, the name can be shadowed by the same name in the inner scope. I'm not asking about grammatical difference, but the reason for this convention. With this level of consistency, I am expecting that there is a reason for it, and I want to know why.
Members almost always found without prefix:
document
console
setTimeout()
alert()
fetch()
with prefix:
window.location
window.onload
window.open()
It is a question relates to the scopes of Javascript.
The scopes are like this
----------foo------------
| var location |
| |
| ------bar---------------
| | window.location |
| | |
| | -------baz----------
| | | location = '' |
| | | |
| | --------------------
| |-----------------------|
|------------------------|
foo, bar and baz
are all functions(or blocks for const
and let
), so If I want to access global(window for example) things(property or method), I need to use window.xxx
, otherwise, a user-defined thing may be referenced, for example the location
defined in foo
function.
For these members:
Members almost always found without prefix:
document
console
setTimeout()
alert()
fetch()
Because:
document
)with prefix:
window.location
window.onload
window.open()
Because:
window.open
vs open
, open what? WINDOW!! The code said so.
The current scope may give you a custom method defined in window
, AKA shadowing
, you may want to use that.
function foo () {
function alert (sth) {
console.log(`alert:${sth}`)
window.alert(sth)
}
alert('I am Carebear.')
}
foo()
Imagine a library or your friends defined a custom alert
which is 100% compatible with the window.alert
. Calling alert without window can leverage it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With