Which of the following should I use to assign the location
object to a local variable in javascript?
var l = location;
var l = window.location;
var l = window.document.location;
Why are there so many methods? Is there any difference?
Which of the following should I use to assign the location
object to a local variable in javascript?
var l = location;
var l = window.location;
var l = window.document.location;
Why are there so many methods? Is there any difference?
I would use window.location
, to help ensure I was really talking about the global object's property, and not some local variable which happens to be called location
.
The W3C specs say:
The location attribute of the Window interface must return the Location object for that Window object's Document.
so those two are indeed equivalent (in fact exactly the same object).
location
just happens to be a short hand for window.location
, so long as there's no other variable named location
in the scope.
They all refer to the same object. Though, window.location
is more explicit, cross browser compliant and can prevent collisions with other variables named location
in different scopes.
Why so many ways?
Browser differences/vestigial remnants from a bygone era.
In a web browser, window
is always at the top of the variable lookup chain. Thus, a global variable x
is also window.x
. For example:
<script>
var x = 1;
window.alert(window.x);
</script>
Will alert 1
. Similarly, location
will also resolve as window.location
provided there is no more local variable called location
in the chain.
window.location is the _top location. document.location is the current html page location
if you are in an iframe document.location of the iframe will differ because window.location refers to the parent page.
by having a check on this you can break from frames by checking if the are te same. if not break from unauthorised framing. or check if my parent page for the i frame is the right one, if not redirect to the right one.