在浏览器中仅使用位置与使用window.location是否有任何区别

Cod*_*gue 6 javascript window.location javascript-objects

我发现自己总是写作:

console.log(window.location.href);
Run Code Online (Sandbox Code Playgroud)

甚至没有考虑过它.关于SO的大多数答案也是这样写的.我有什么理由不能写:

location.href
Run Code Online (Sandbox Code Playgroud)

既然location是窗口级别的对象?这有什么跨浏览器兼容性问题吗?

澄清:我知道有document.location- 这不是这个问题的内容.这location与使用window.location跨浏览器仅使用vs 有任何区别.

Tib*_*bos 13

有一些差异.

在全球范围内,它们之间绝对没有区别,但在其他情况下,您可能遇到麻烦:

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

这源于这样的事实:如果你在没有用窗口作为前缀的情况下编写位置,它将通过每个范围来查找名为location的变量.最终它会在窗口中找到它,除非另一个范围也声明了一个.显然反过来也是如此:

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

我更喜欢用窗口作为全局变量的前缀,因为这样我立即知道它们是全局的,并且因为当我找到一个没有窗口前缀的全局变量时,我知道这是一个缺少var的拼写错误,但这纯粹是个人喜好.