Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to and not to specify "window." prefix for window property and methods

Tags:

javascript

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()
like image 905
Affinity Avatar asked Mar 08 '20 04:03

Affinity


1 Answers

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:

  1. We treat them as function or constant(document)
  2. We don't mutate anything, we just call a function or read something.

with prefix:

window.location
window.onload
window.open()

Because:

  1. We do mutate something.
  2. We treat them as object properties.
  3. More descriptive, compare window.open vs open, open what? WINDOW!! The code said so.

Another reason

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.

like image 177
wolfrevo Avatar answered Oct 29 '22 16:10

wolfrevo