javascript window.location 与仅位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4709037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.location versus just location
提问by Reid
Across the web, I see a vast number of JavaScript programmers writing window.locationinstead of just location. I was curious if anyone could offer an explanation as to why. windowis the global object, and therefore it is unnecessary to include -- isn't it? I mean, you don't see people write window.Math.flooror new window.Date(), so I'm curious as to why it would be specified with location.
在网络上,我看到写JavaScript程序员的大量window.location而不仅仅是location。我很好奇是否有人可以解释原因。window是全局对象,因此没有必要包含 -- 不是吗?我的意思是,你看不到人们写window.Math.flooror new window.Date(),所以我很好奇为什么它会被指定为location.
I understand that locationis 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 locationin the first place, not without redirecting the page.
我知道这location被认为是您所在窗口的“财产”,我认为这是有道理的。但即便如此,我也没有任何理由指定全局对象;首先不可能覆盖location,除非重定向页面。
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...
那么,这只是一个已经使用了很长时间以至于它与我们编写 JavaScript 的方式集成在一起的怪癖,还是有一些切实的理由来这样做?我查了谷歌,但唉,我什么也没想到......
回答by lonesomeday
I always use window.locationin my code for two principal reasons:
我总是window.location在我的代码中使用有两个主要原因:
- 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. - 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 locationsomewhere in a containing scope (it's not an unlikely word to use as a variable name) and you'd be working on that instead.
- 尽可能避免使用全局变量是一个好习惯。使用
window.前缀提醒我变量是全局的,而其他变量不是。 - Javascript 作用域的性质允许您覆盖在作用域树上设置的变量。这意味着您可以
var location在包含范围内的某处进行设置(这不是一个不太可能用作变量名的词),而您将改为进行处理。
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.
对我来说,编码时明确的目的非常重要,因为它可以帮助我避免编写错误,然后帮助我在编写错误时找到它们。
回答by user113716
Partly for safety in case someone defines a locationvariable somewhere in the scope chain. the window.locationmakes it an explicit reference to the property of window.
部分是为了安全,以防有人location在作用域链中的某处定义变量。将window.location使它成为一个明确提及的财产window。
Example:http://jsfiddle.net/dr6KH/
示例:http : //jsfiddle.net/dr6KH/
(function() {
var location = 'new value'; // creating a local variable called "location"
(function() {
alert(location); // alerts "new value"
alert(window.location); // alerts the toString value of window.location
})();
})();
回答by Tim Down
There's a big difference between window.locationand the native Mathand Dateobjects, which is that Mathand Dateare native JavaScript objects that are specified to exist as properties of the global object, while window.locationis a property of the windowhost object(a host object is an object representing some aspect of the environment, provided by the environment, and is not subject to the same rules as native JavaScript objects. Other host objects include documentand any DOM element).
window.location和 nativeMath和Dateobjects之间有很大的区别,即Math和Date是本地 JavaScript 对象,被指定为全局对象window.location的属性,而是window宿主对象的属性(宿主对象是表示某些方面的对象)由环境提供的环境,不受与原生 JavaScript 对象相同的规则约束。其他宿主对象包括document和任何 DOM 元素)。
windowin browsers serves two purposes: first, acting as the (well-specified) ECMAScript global object, and second, acting as a host object providing information about the browser environment. For uses of windowin its host object capacity, I prefer to be explicit and provide the window.prefix: the fact that locationworks without it is just a coincidence that comes from window's schizophrenic nature. Also, as pointed out by other answers, this also has the advantage of protecting you in the case when another locationvariable exists in the current context.
window在浏览器中有两个目的:首先,充当(明确指定的)ECMAScript 全局对象,其次,充当提供有关浏览器环境的信息的宿主对象。对于window在其宿主对象容量中的使用,我更愿意明确并提供window.前缀:location没有它也能工作的事实只是巧合,它来自window精神分裂症的性质。此外,正如其他答案所指出的那样,这也具有location在当前上下文中存在另一个变量的情况下保护您的优势。
One good reason for not prefixing Dateor Mathwith window.is that doing so creates code that does not work in a non-browser environment. Other environments generally do not provide windowas an alias for the global object.
不加前缀Date或Math使用前缀的一个很好的理由window.是,这样做会创建在非浏览器环境中不起作用的代码。其他环境一般不提供window作为全局对象的别名。
回答by fuzzyTew
Part of coding is clarity. Unlike Math or Date, location is conceptually a property of the window, so the code becomes more clear to include it. The "window." prefix should ideally be removed for minification.
编码的一部分是清晰。与数学或日期不同,位置在概念上是窗口的一个属性,因此包含它的代码会变得更加清晰。窗户。” 理想情况下应该删除前缀以进行缩小。
You are probably correct that a lot of the reason is historical. Javascript has an extensive history of copying and pasting.
您可能是正确的,很多原因都是历史原因。Javascript 在复制和粘贴方面有着悠久的历史。
回答by rhurkes
It is not always just a matter of style - I was trying to load social media buttons asynchronously after the window's load event by appending script elements to a fragment, and then appending that fragment to the document. Twitter's widgets.js uses location.hrefin several places and was causing the following error in IE 8/9: Unexpected call to method or property access. I haven't figured out why, but this only happens when visiting the page via a link from another page. If you just append the script element to the head or use window.location.href, this doesn't occur, so it appears to be some weirdness with IE 8/9 and createDocumentFragment().
这并不总是只是风格问题 - 我试图通过将脚本元素附加到片段,然后将该片段附加到文档,在窗口的加载事件之后异步加载社交媒体按钮。Twitter 的 widgets.jslocation.href在多个地方使用,并在 IE 8/9 中导致以下错误:Unexpected call to method or property access。我还没有弄清楚原因,但这只会在通过另一个页面的链接访问该页面时发生。如果您只是将脚本元素附加到 head 或 use window.location.href,则不会发生这种情况,因此 IE 8/9 和createDocumentFragment().
Example:
例子:
<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.stackoverflow.com">Tweet</a>
<script>
(function (d, t) {
var head = document.getElementsByTagName('head')[0];
var frag = d.createDocumentFragment();
var s = d.createElement(t);
s.async = true;
s.src = 'http://platform.twitter.com/widgets.js';
frag.appendChild(s);
head.appendChild(frag);
} (document, 'script'));
</script>
回答by Jacob Relkin
The windowobject is the default working namespace, so locationwill be equal to window.location.
该window对象是默认的工作命名空间,因此location将等于window.location.
I think that using locationis a bit ambiguous, use window.locationfor clarity.
我认为使用location有点模棱两可,window.location为了清楚起见。
回答by SLaks
It's just a matter of style.
这只是风格问题。
Conceptually, locationis a property of the window(the window is at a location), unlike Mathor Date.
从概念上讲,location是 的属性window(窗口位于某个位置),与Math或不同Date。
回答by arlomedia
location is a property of the window object, so you can get it by requesting window.location. But if you don't specify an object, JavaScript assumes you want the window object. So just requesting location is the same as requesting window.location.
location 是 window 对象的一个属性,所以可以通过请求 window.location 来获取。但是如果你没有指定一个对象,JavaScript 会假设你需要 window 对象。所以只是请求位置和请求 window.location 是一样的。

