繁体   English   中英

在函数内部定义一个未定义的全局变量

[英]defining an undefined global variable inside a function

这是一堆乱七八糟的东西(不是我的代码,但我坚持下去)。 函数取决于全局定义的变量。

function variableIssues(){
    alert(someGlobalString);  // alerts "foo"
}

有时,此全局定义的变量是undefined 在这种情况下,我们希望将其转换为进一步处理。 该功能已修改。

function variableIssues(){
    alert(someGlobalString); // undefined

    if (!someGlobalString){
        var someGlobalString = "bar";
    }  
}

但是,如果现在使用已定义的someGlobalString调用此函数,则由于JavaScript评估,该变量设置为undefined并且始终设置为bar

function variableIssues(){
    alert(someGlobalString); // "should be foo, but javascript evaluates a 
                             // variable declaration it becomes undefined"

    if (!someGlobalString){
        var someGlobalString = "bar";
    }  
}

我想获得一些有关如何处理undefined全局变量的建议。 有任何想法吗?

全局变量是window对象的属性,因此可以使用window显式访问它们:

if (!window.someGlobalString) {
// depending on possible values, you might want:
// if (typeof window.someGlobalString === 'undefined')
    window.someGlobalString = "bar";
}

如果您正在使用全局变量,那么这是更好的样式,因为很清楚您在做什么,并且将其分配给未定义的全局变量在严格模式下不会引发错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM