Difference between [removed] and location.href

前端 未结 6 1395
一个人的身影
一个人的身影 2020-12-01 07:35

I am confused as to the difference between window.location and location.href. Both appear to be acting in the same way.

What is the differe

相关标签:
6条回答
  • 2020-12-01 07:49

    You are accessing the same object. Its some kind of a shortcut. If you use firebug (or similar) to change its "hash" property, you'll see that it gets changed in both places.

    Technically, your default scope is the window object, so when you access "location.href" you are accessing to window.location.href.

    0 讨论(0)
  • 2020-12-01 07:50

    window.location has other properties aside from href but if you assign window.location a URL it will redirect.

    You can see all of its properties in MDN (like search, protocol, hash, ...)

    0 讨论(0)
  • 2020-12-01 07:50

    Check this old MDN article:

    Location objects have a toString method returning the current URL. You can also assign a string to window.location. This means that you can work with window.location as if it were a string in most cases. Sometimes, for example when you need to call a String method on it, you have to explicitly call toString:

    window is just the global object that houses several properties, one of them is location. location also has properties, one of them is href. location.href is just window.location.href

    0 讨论(0)
  • 2020-12-01 07:55

    They are different. window.location is an object containing the property href which is a string.

    Setting window.location and window.location.href behave the same way, as you noticed, because it was built into the JavaScript language long ago. Read more in this question about setting window.location.

    Getting window.location and window.location.href behave differently because the former is an object and the latter is a string. If you run string functions like indexOf() or toLowerCase(), you have to use window.location.href.

    0 讨论(0)
  • 2020-12-01 07:55

    location.href property returns the entire URL of the current page.

    Where as

    window.location property represents the currect location of the window object, if you change this you will get redirected.

    0 讨论(0)
  • 2020-12-01 08:14

    window.location is an object that holds all the information about the current document location (host, href, port, protocol etc.).

    location.href is shorthand for window.location.href (you call location from global object - window, so this is window.location.href), and this is only a string with the full URL of the current website.

    They act the same when you assign a URL to them - they will redirect to the page which you assign, but you can see differences between them when you open the browser console (firebug or developer tools) and write window.location and location.href.

    0 讨论(0)
提交回复
热议问题