在JSFiddle中,为什么未在`window`上定义此全局变量? [英] In JSFiddle, why is this global variable not defined on `window`?
问题描述
我有此代码在小提琴中:
var a = 1;
function b() {
var a = 10;
alert(window.a);
}
b();
为什么在这里未定义a
?它已经在全局名称空间(即window
)中定义. (有关这种意外行为的示例,请参见小提琴.)
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.)
推荐答案
如果您正在未将位置设置为不自动换行"的小提琴中运行此代码,或者在任何情况下在顶级范围内,您的外部a
不是不是全局变量window.a
.考虑一个简单的示例,其中代码包装在名为wrappingFunc
的函数中:
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();
当您将位置设置为onLoad
或onDomready
时,这正是JSFiddle所做的. (请参阅什么是onLoad,onDomready,< head中没有换行和< body>中没有换行之间的区别?)我的wrappingFunc
示例实际上是onload
或ondomready
侦听器函数,这会阻止Keep在全局上下文中运行.
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.
这篇关于在JSFiddle中,为什么未在`window`上定义此全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!