Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of referencing the window object in Javascript?

Tags:

javascript

Every property of the window object is a global variable. This means you can do something like this:

window.foo = 42;
alert(foo); //alerts 42
var bar = 3;
alert(window["bar"]); //alerts 3

Because of this, I've always wondered what the purpose was of referencing window in code like this

if(window.prompt("Enter Password") === "secret") {
  window.location.hash = "authorized";
  window.open("secretPage.html");
}

when you could omit window and have code that does exactly the same thing:

if(prompt("Enter Password") === "secret") {
  location.hash = "authorized";
  open("secretPage.html");
}

The use also seems inconsistent; I almost never see window.alert but I'll frequently see window.location.

Do people just like referencing window to make their code more verbose? Is there some good reason for doing this that I don't know about?

like image 526
Peter Olson Avatar asked Jan 27 '12 23:01

Peter Olson


2 Answers

One situation in which it helps to be explicit is that it will be immediately clear inside a function that you intend to modify a global variable. For example:

function blah() {
    // a bunch of code preceding...
    test = "aha!";
}

Did someone forget to declare test with var? Or is this intentional modification of a global? Compare:

function blah() {
    // a bunch of code preceding...
    window.test = "aha!";
}

Now it's immediately clear what is intended. Of course, you know, globals should be avoided in the first place, but you get my point.

like image 153
Wayne Avatar answered Oct 04 '22 17:10

Wayne


window is implicit, but it's good code practice to avoid ambiguity where possible.

like image 44
Silas Hansen Avatar answered Oct 04 '22 18:10

Silas Hansen