[removed] Setting location.href versus location

后端 未结 7 1708
野性不改
野性不改 2020-11-22 17:16

When would you set location to a URL string versus setting location.href?

location = \"http://www.stackoverflow.com\";
相关标签:
7条回答
  • 2020-11-22 17:43

    One difference to keep in mind, though.

    Let's say you want to build some URL using the current URL. The following code will in fact redirect you, because it's not calling String.replace but Location.replace:

    nextUrl = window.location.replace('/step1', '/step2');
    

    The following codes work:

    // cast to string
    nextUrl = (window.location+'').replace('/step1', '/step2');
    
    // href property
    nextUrl = window.location.href.replace('/step1', '/step2');
    
    0 讨论(0)
  • 2020-11-22 17:45

    Just to clarify, you can't do location.split('#'), location is an object, not a string. But you can do location.href.split('#'); because location.href is a string.

    0 讨论(0)
  • 2020-11-22 17:46

    With TypeScript use window.location.href as window.location is technically an object containing:

    Properties
    hash 
    host 
    hostname
    href    <--- you need this
    pathname (relative to the host)
    port 
    protocol 
    search 
    

    Setting window.location will produce a type error, while window.location.href is of type string.

    Source

    0 讨论(0)
  • 2020-11-22 17:53

    Even if both work, I would use the latter. location is an object, and assigning a string to an object doesn't bode well for readability or maintenance.

    0 讨论(0)
  • 2020-11-22 17:57

    A couple of years ago, location did not work for me in IE and location.href did (and both worked in other browsers). Since then I have always just used location.href and never had trouble again. I can't remember which version of IE that was.

    0 讨论(0)
  • 2020-11-22 17:59

    You might set location directly because it's slightly shorter. If you're trying to be terse, you can usually omit the window. too.

    URL assignments to both location.href and location are defined to work in JavaScript 1.0, back in Netscape 2, and have been implemented in every browser since. So take your pick and use whichever you find clearest.

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