Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - Is there any difference with using only location vs using window.location across browsers

I find myself always writing:

console.log(window.location.href);

without even thinking about it. The majority of answers on SO also write it this way. Is there any reason why I can't just write:

location.href

since location is an object at window level? Are there any cross-browser compatibility issues with this?

To Clarify: I know there is document.location - that is NOT what this question is about. This is about if there is any difference with using only location vs using window.location across browsers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are some differences.

In global scope, there is absolutely no difference between them, but in other cases you might get in trouble:

function () {
  var location = { 'href' : '123' } ;
  console.log(window.location.href) // actual url
  console.log(location.href) // '123'
}

This stems from the fact that if you write location without prefixing it with window, it will go up through every scope to find a variable named location. Eventually it will find it in window, unless another scope declared one as well. Obviously the reverse is true as well:

function () {
  var window = { 'location' : { 'href': '123' } };  
  console.log(window.location.href) // '123'
  console.log(location.href) // actual url
}

I for one prefer to prefix the global variables with window because that way i immediately know they are global and also because when i find a global variable that is not prefixed with window, i know it is a typo missing a var, but that is purely personal preference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...