window.location与只是位置 [英] window.location versus just location

查看:156
本文介绍了window.location与只是位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网络上,我看到大量的JavaScript程序员编写 window.location 而不是 location 。我很好奇是否有人可以提供解释原因。 window 是全局对象,因此不必包含 - 不是吗?我的意思是,你没有看到人们写 window.Math.floor 新window.Date(),所以我很好奇为什么用 location 指定它。

Across the web, I see a vast number of JavaScript programmers writing window.location instead of just location. I was curious if anyone could offer an explanation as to why. window is the global object, and therefore it is unnecessary to include -- isn't it? I mean, you don't see people write window.Math.floor or new window.Date(), so I'm curious as to why it would be specified with location.

我明白 location 被认为是你所在窗口的属性,我认为这是有道理的。但即便如此,我也没有理由指定全局对象;首先不可能覆盖 location ,而不是没有重定向页面。

I understand that location is considered to be a "property" of the window you're in, which I suppose makes some sense. But even so, I don't see any reason to specify the global object; it's not possible to overwrite location in the first place, not without redirecting the page.

所以,这只是一个已经使用了很长时间以至于它与我们编写JavaScript的方式集成在一起的怪癖,还是有一些切实的理由以这种方式做事?我查了一下谷歌,但是唉,我什么都没想出来......

So, is this just a quirk that has been used for so long that it's become integrated with how we write JavaScript, or is there some tangible reason to do things this way? I checked Google, but alas, I came up with nothing...

推荐答案

我总是使用窗口.location 在我的代码中有两个主要原因:

I always use window.location in my code for two principal reasons:


  1. 尽可能避免全局变量是一个好习惯。使用窗口。前缀提醒我变量是全局的,而其他变量不是。

  2. Javascript的范围允许你覆盖范围树上方设置的变量。这意味着您可以在包含范围内的某处设置 var location (这不是一个不太可能用作变量名的单词),而是您正在研究它。

  1. It's a good habit to avoid global variables whenever possible. Using the window. prefix reminds me that the variable is global and that others aren't.
  2. The nature of Javascript's scoping allows you to override variables set higher up the scope tree. This means that you could have set var location somewhere in a containing scope (it's not an unlikely word to use as a variable name) and you'd be working on that instead.

对我而言,编码时目的明确非常重要,因为它可以帮助我避免编写错误然后帮助我找到它们。

For me, clarity of purpose when coding is very important as it helps me avoid writing bugs and then helps me find them when I do.

这篇关于window.location与只是位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆