Chrome 13 中全局定义的位置
当我输入以下行时,我正在使用 Chrome 13 中的开发人员工具:
var location = "Hello";
按下 Enter 键后,页面发生更改并给了我 404 错误。地址栏现在已将 Hello
附加到最后一个地址。
我发誓我已经在 Chrome 中输入了完全相同的行过去并没有遇到同样的问题。我以为位置是window.location
。
有什么变化吗,或者我以前从未注意到这一点?
I was using the Developer Tools in Chrome 13 when I typed this line:
var location = "Hello";
Upon pressing enter, the page changed and gave me a 404 error. The address bar now had Hello
appended to the last address.
I swear that I have typed the exact same lines into Chrome in the past and not had the same problem. I thought location was at window.location
.
Has something changed, or have I just never noticed this before?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
开发人员工具中的上下文是
window
,这是完全正常的。输入this
并查看内容。它可能是窗口
。因此,当您键入:
您正在尝试重新定义全局范围内已存在的变量。浏览器中的全局范围是
window
对象。因此,全局范围内的location
与window.location
相同。尝试重新定义已经存在的对象(通过使用
var
)在 javascript 中不是错误。它只是忽略 var 声明并进行赋值。并且,将字符串分配给位置对象,转到新网页。It's perfectly normal that the context in the developer tools would be
window
. Typethis
and see what is says. It's probablywindow
.Thus, when you type:
You are trying to redefine a variable in the global scope that already exists. The global scope in a browser is the
window
object. Thus,location
in the global scope is the same aswindow.location
.Trying to redefine an object that already exists (by using
var
) is not an error in javascript. It just ignores thevar
declaration and does an assignment. And, assigning a string to the location object, goes to a new web page.Chrome 可能更改了其范围规则。我不清楚控制台上的 var 是否应该被视为窗口作用域或某些神秘的控制台作用域。
如果要创建名为 location 的变量,则应该创建一个安全范围,例如通过使用立即函数。例如
Chrome may have changed its scoping rules. It's unclear to me whether
var
on the console should be treated as window scope or some mysterious console scope.If you want to create a variable named location, you should create a safe scope, for example by using an immediate function. E.g.