Chrome 13 中全局定义的位置

发布于 2024-12-04 18:01:32 字数 373 浏览 0 评论 0原文

当我输入以下行时,我正在使用 Chrome 13 中的开发人员工具:

var location = "Hello";

按下 Enter 键后,页面发生更改并给了我 404 错误。地址栏现在已将 Hello 附加到最后一个地址。

http://www.google.com/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.

http://www.google.com/Hello

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏夜暖风 2024-12-11 18:01:32

开发人员工具中的上下文是window,这是完全正常的。输入 this 并查看内容。它可能是窗口

因此,当您键入:

var location = "Hello";

您正在尝试重新定义全局范围内已存在的变量。浏览器中的全局范围是window对象。因此,全局范围内的locationwindow.location相同。

尝试重新定义已经存在的对象(通过使用 var)在 javascript 中不是错误。它只是忽略 var 声明并进行赋值。并且,将字符串分配给位置对象,转到新网页。

It's perfectly normal that the context in the developer tools would be window. Type this and see what is says. It's probably window.

Thus, when you type:

var location = "Hello";

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 as window.location.

Trying to redefine an object that already exists (by using var) is not an error in javascript. It just ignores the var declaration and does an assignment. And, assigning a string to the location object, goes to a new web page.

夜光 2024-12-11 18:01:32

Chrome 可能更改了其范围规则。我不清楚控制台上的 var 是否应该被视为窗口作用域或某些神秘的控制台作用域。

如果要创建名为 location 的变量,则应该创建一个安全范围,例如通过使用立即函数。例如

(function(){
  var location = "hello";  // safe
})();

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.

(function(){
  var location = "hello";  // safe
})();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文