window.location和document.location有什么区别?它们是否都应该引用相同的对象?
window.location和document.location有什么区别?它们是否都应该引用相同的对象?
window.location
而不是document.location
。获取当前位置对象的规范方法是 window.location
(参见1996年的此MSDN页面和2006年的W3C草案)。
相较于最初仅返回当前URL字符串的 document.location
(请参见这个MSDN页面),很可能为了避免混淆,document.location
被替换成了 document.URL
(请参见此MSDN页面),它也是DOM Level 1的一部分。
据我所知,所有现代浏览器将 document.location
映射到 window.location
,但我仍然更喜欢使用 window.location
,因为这是我从编写我的第一个 DHTML 开始就一直在使用的。
window.location
,那么仅使用 location
是否同样有效呢? - commonpikewindow
对象。因此,在脚本的顶层定义的任何变量或函数都是window
对象的属性,而window
对象恰好是全局对象。如果省略全局对象,它将被隐含地认为是window.
,所以location
被解释为window.location
。需要注意的是,例如if(an_undefined_variable)
会在变量未定义时抛出错误,但是if(window.an_undefined_variable)
不会。 - Armen Michaeliwindow.location在所有兼容的浏览器中都是可读写的。
document.location在Internet Explorer (至少)中只能读取,但在基于Gecko的浏览器 (Firefox, SeaMonkey) 中是可读写的。
有趣的是,如果你有一个名为 'location' 的frame、image或form,那么'document.location'会分别提供对应的frame窗口、image或form的引用,而不是Location对象。显然,这是因为document.forms、document.images和window.frames集合名称查找优先于映射到window.location。
<img name='location' src='location.png'>
if (document.location.tagName == 'IMG') alert('Hello!')
window.location
和document.location
。 - Mr. Llamawindow.location
而不是 document.location
。document.location
映射到 window.location
,但我仍然更喜欢使用 window.location
,因为这是我编写第一个网页时就使用的方式,它更加一致。document.location === window.location
返回 true
,这澄清了两者是相同的。document.location === window.location
返回 true
另外
document.location.constructor === window.location.constructor
也是 true
注意:这是在测试了 Chrome、Firefox 3.6、Opera 10 和 IE6 后得出的结论。
===
和 ==
是等价的。 - Mark Amery"abc" == new String("abc")
返回 true
,而 "abc" === new String("abc")
返回 false
。 - Pacerier==
和===
是等价的。参见规范的11.9.3和11.9.6章节。对于非null、非undefined、非数字、非布尔、非字符串类型的值,它们具有相同的类型,==
的行为受11.9.3部分1f的约束,而===
的行为则受11.9.6部分7的约束,这两部分都是完全相同的:如果x和y引用了同一个对象,则返回true。否则,返回false。 - Mark Amerydocument.location
和window.location
都指向对象。你错过了全等符号的整个意义;使用两个等于号不能证明它们是同一个对象。我们应该使用三个等号而不是两个等号,因为两个等号会给我们一个错误的结果。在一个浏览器中,其中document.location
是一个与window.location.toString()
相等的URL字符串时,document.location==window.location
将返回true,而document.location===window.location
将返回false。 - Pacerierdocument.location === window.location
比较方面是这样的。.constructor
比较也被加入其中,我认为这个答案仍然是正确的,但使用 ===
会简化推理过程。 - Mark Amery是的,它们是相同的。这是浏览器JS API中许多历史怪癖之一。尝试执行:
window.location === document.location
window.location是两者中更加可靠且一致的,特别是对于旧浏览器而言。
如今很少见到这种区别,因为HTML 5不再支持框架集。但是在过去,当我们还有框架集时,document.location只会重定向执行代码的框架,而window.location则会重定向整个页面。