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

天大地大妈咪最大 提交于 2019-12-17 19:46:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19423513/is-there-any-difference-with-using-only-location-vs-using-window-location-across

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!