在JSFiddle中,为什么这个全局变量没有在`window`上定义?

时间:2015-10-12 11:45:14

标签: javascript scope jsfiddle

我有this code in a fiddle

var a = 1;  

function b() {  
    var a = 10;  
    alert(window.a);  
}  

b();  

为什么a在这里未定义?它已在全局命名空间中定义,即window。 (有关此意外行为的示例,请参阅the fiddle。)

1 个答案:

答案 0 :(得分:3)

如果你在没有将位置设置为"没有换行"的小提琴中运行此代码,或者您不在顶级范围内的任何情况,您的外部a 全局变量window.a。考虑一个简单的示例,其中您的代码包含在名为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();

这正是JSFiddle在您将位置设置为onLoadonDomready时所执行的操作。 (请参阅What is the difference between onLoad, onDomready, No wrap - in <head>, and No wrap - in <body>?)我的wrappingFunc示例实际上是一个onloadondomready侦听器函数,它可以阻止Keep在全局上下文中运行。

相关问题