Across the web, I see a vast number of JavaScript programmers writing window.location
instead of just location
. I was curious if anyone could offer an explanation as to why. window
is the global object, and therefore it is unnecessary to include -- isn't it? I mean, you don't see people write window.Math.floor
or new window.Date()
, so I'm curious as to why it would be specified with location
.
I understand that location
is considered to be a "property" of the window you're in, which I suppose makes some sense. But even so, I don't see any reason to specify the global object; it's not possible to overwrite location
in the first place, not without redirecting the page.
So, is this just a quirk that has been used for so long that it's become integrated with how we write JavaScript, or is there some tangible reason to do things this way? I checked Google, but alas, I came up with nothing...
window. location is read/write on all compliant browsers. document. location is read-only in Internet Explorer (at least), but read/write in Gecko-based browsers (Firefox, SeaMonkey).
The location property of a window (i.e. window. location ) is a reference to a Location object; it represents the current URL of the document being displayed in that window. Since window object is at the top of the scope chain, so properties of the window.
The window. location object can be used to get the current page address (URL) and to redirect the browser to a new page.
I always use window.location
in my code for two principal reasons:
window.
prefix reminds me that the variable is global and that others aren't.var location
somewhere in a containing scope (it's not an unlikely word to use as a variable name) and you'd be working on that instead.For me, clarity of purpose when coding is very important as it helps me avoid writing bugs and then helps me find them when I do.
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