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

时间:2013-02-15 10:14:16

标签: javascript variables casting scope operator-precedence

这是杂乱的东西(不是我的代码,但我坚持它)。函数取决于全局定义的变量。

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全局变量提出一些建议。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

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

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

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

相关问题