Location globally defined in Chrome 13
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
.
H开发者_如何学编程as something changed, or have I just never noticed this before?
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.
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
})();
精彩评论