8

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.

4

1 回答 1

16

有一些差异。

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

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

这源于这样一个事实,如果您编写 location 时没有在其前面加上 window 前缀,它将遍历每个范围以找到一个名为 location 的变量。最终它将在窗口中找到它,除非另一个范围也声明了一个。显然,反过来也是正确的:

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

我更喜欢给全局变量加上 window 前缀,因为这样我立即知道它们是全局的,而且当我找到一个没有以 window 前缀的全局变量时,我知道这是一个缺少 var 的错字,但这纯粹是个人喜好。

于 2013-10-17T10:10:30.480 回答