窗口之间有什么区别。Location和document。Location ?它们是否都引用同一个对象?
当前回答
文档。Location ===窗口。Location返回true
also
Document.location.constructor === window.location.constructor为true
注:仅在Firefox 3.6、Opera 10和IE6上测试
其他回答
是的,它们是一样的。这是浏览器JS API的众多历史怪癖之一。试着做:
window.location === document.location
文档。Location ===窗口。Location返回true
also
Document.location.constructor === window.location.constructor为true
注:仅在Firefox 3.6、Opera 10和IE6上测试
尽管大多数人在这里推荐,这就是谷歌Analytics的动态协议剪辑的样子(在他们最近从ga.js转移到analysis .js之前):
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
更多信息:https://developers.google.com/analytics/devguides/collection/gajs/
在新版本中,他们使用了'//',所以浏览器可以自动添加协议:
'//www.google-analytics.com/analytics.js'
如果谷歌更喜欢document。窗口的位置。当他们需要JS中的协议时,我猜他们有一些原因。
总的来说:我个人相信这份文件。位置和窗口。位置是相同的,但如果巨人与最大的统计使用浏览器像谷歌使用文档。地点,我建议遵循他们。
我想说是窗户。location是更可靠的获取当前URL的方式。 下面是窗口的区别。位置和文档。在其中一个场景中,我在url中添加哈希参数,然后读取它。
在URL中添加散列参数后。
在较旧的浏览器中,我无法通过使用document从URL获得散列参数。url,但当我使用窗口。然后我就能从URL中得到哈希参数。
所以最好使用window。location。
我更喜欢使用文档。位置,尽管位置,文档。位置和窗口。Location返回相同的对象。
使用文件的原因。地点是:
窗口的浏览器兼容性部分。位置提到
在Firefox 57之前,通过URL api访问URL时,URL中包含的单引号会被转义。参见bug 1386683。
文档的浏览器兼容性部分。位置提到
全力支持。
Mdn location reference uses document.location in their examples. // location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container const loc = document.location; console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container console.log(loc.protocol); // https: console.log(loc.host); // developer.mozilla.org:8080 console.log(loc.hostname); // developer.mozilla.org console.log(loc.port); // 8080 console.log(loc.pathname); // /en-US/search console.log(loc.search); // ?q=URL console.log(loc.hash); // #search-results-close-container console.log(loc.origin); // https://developer.mozilla.org:8080 location.assign('http://another.site') // load another page