首页 > window.location 和 window.location.href区别是什么

window.location 和 window.location.href区别是什么

window.location 和 window.location.href区别是什么


前者返回一个对象,后者返回一个字符串


window.location是一个对象,包含属性有

hash 从井号 (#) 开始的 URL(锚)
host 主机名和当前 URL 的端口号
hostname 当前 URL 的主机名
href 完整的 URL
pathname 当前 URL 的路径部分
port 当前 URL 的端口号
protocol 当前 URL 的协议
search 从问号 (?) 开始的 URL(查询部分)

获取window.location.href是最常用的


题主是不是疑惑他们的输出是一样的?

当输出 location 时,会调用 toString() 函数,返回的值是 a DOMString containing the whole URL

而 location.href 表示 a DOMString containing the whole URL.

所以值是一样的。

参考

https://developer.mozilla.org/en-US/docs/Web/API/Location


The Window.location read-only property returns a Location object with
information about the current location of the document.

Though Window.location is a read-only Location object, you can also
assign a DOMString to it. This means that you can work with location
as if it were a string in most cases
: location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'.

https://developer.mozilla.org/en-US/docs/Web/API/Window/location

location 是 location.href 的簡寫,無論是訪問 還是賦值。

從功能上,location 等於 location.href;

但從本體論上,location 是一個對象,location.href 是它的一個屬性。

這種怪異的行爲應該是爲了兼容無疑


在chrome的console里面输入 window.location.href和window.location你就能很清楚的看到两者的不同


location是一个对象,href是location下面的一个属性,同理还有host,queryString等


吐槽下:还在人用alert来查看变量啊?这种问题,按F11打开控制台,在控制台中输一下,直接输入对应的变量 -- 哇,变量具体内容全都打出来了

【热门文章】
【热门文章】