问题
I have this code in a fiddle:
var a = 1;
function b() {
var a = 10;
alert(window.a);
}
b();
Why is a
is undefined here? It's already defined in global namespace, i.e., window
. (See the fiddle for an example of this unexpected behavior.)
回答1:
If you're running this code in a fiddle that does not have the location set to "No wrap", or any circumstance in which you're not at the top-level scope, your outer a
is not the global variable window.a
. Consider a simple example where your code is wrapped inside a function called wrappingFunc
:
// THIS would be the global `a`, outside `wrappingFunc`
var a = "now the global a is defined";
function wrappingFunc() {
// this is NOT the global `a`
var a = 1;
function b() {
var a = 10;
alert(window.a);
}
b();
}
wrappingFunc();
This is exactly what JSFiddle does when you set the location to onLoad
or onDomready
. (See What is the difference between onLoad, onDomready, No wrap - in <head>, and No wrap - in <body>?) My wrappingFunc
example is in actuality an onload
or ondomready
listener function, which prevents the keep from running in a global context.
来源:https://stackoverflow.com/questions/33080320/in-jsfiddle-why-is-this-global-variable-not-defined-on-window