In JSFiddle, why is this global variable not defined on `window`?

蓝咒 提交于 2019-12-14 01:38:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!