本文翻译自:Javascript: Setting location.href versus location
When would you set location
to a URL string versus setting location.href
? 您何时将location
设置为URL字符串而不是setting location.href
?
location = "http://www.stackoverflow.com";
vs 与
location.href = "http://www.stackoverflow.com";
Mozilla Developer Network Reference Mozilla开发人员网络参考
#1楼
参考:https://stackoom.com/question/A01x/Javascript-设置location-href与location
#2楼
Like as has been said already, . 就像已经说过的, location
is an object 。 location
是一个对象But that person suggested using either. 但是那个人建议使用两者之一。 But, you will do better to use the .href
version. 但是,使用.href
版本会更好。
Objects have default properties which, if nothing else is specified, they are assumed. 对象具有默认属性,如果没有其他说明,则假定为默认属性。 In the case of the location
object, it has a property called .href
.对于 location
对象,它具有一个名为.href
的属性。And by not specifying ANY property during the assignment, it will assume "href" by default. 通过在分配过程中不指定ANY属性,默认情况下它将采用“ href”。
This is all well and fine until a later object model version changes and there either is no longer a default property, or the default property is changed. 一切都会好起来的,直到以后的对象模型版本更改并且不再有默认属性或更改了默认属性。 Then your program breaks unexpectedly. 然后您的程序意外中断。
If you mean href
, you should specify href
.如果您指的是 href
,则应指定href
。
#3楼
A couple of years ago, location
did not work for me in IE and location.href
did (and both worked in other browsers). 几年前,在IE和location.href
, location
对我不起作用(在其他浏览器中都起作用)。 Since then I have always just used location.href
and never had trouble again. 从那时起,我一直只使用location.href
,再也没有遇到麻烦。 I can't remember which version of IE that was. 我不记得是哪个版本的IE。
#4楼
Just to clarify, you can't do location.split('#')
, location
is an object, not a string. 为了澄清起见,您不能执行location.split('#')
, location
是一个对象,而不是字符串。 But you can do location.href.split('#');
但是您可以执行location.href.split('#');
because location.href
is a string. 因为location.href
是一个字符串。
#5楼
You might set location
directly because it's slightly shorter. 您可能会直接设置location
,因为它的location
略短。 If you're trying to be terse, you can usually omit the window.
如果您要简洁,通常可以省略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. URL分配给location.href
和location
的定义都可以在JavaScript 1.0中使用,也可以在Netscape 2中使用,并且此后已在每个浏览器中实现。 So take your pick and use whichever you find clearest. 因此,请选择并使用最清晰的内容。
#6楼
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.location
是一个对象,为该对象分配字符串对于可读性或维护性而言并不是一个好兆头。