简体   繁体   English

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

[英]defining an undefined global variable inside a function

This is messy stuff (not my code but I'm stuck to it). 这是一堆乱七八糟的东西(不是我的代码,但我坚持下去)。 A function depends on a globally defined variable. 函数取决于全局定义的变量。

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

Sometimes this globally defined variable is, undefined . 有时,此全局定义的变量是undefined In this case we want to cast it for further processing. 在这种情况下,我们希望将其转换为进一步处理。 The function is modified. 该功能已修改。

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

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

However, if this function is now called with a defined someGlobalString, because of javascript evaluation the variable is set to undefined and always get set to 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";
    }  
}

I would like to get some suggestions on how to handle undefined global variable. 我想获得一些有关如何处理undefined全局变量的建议。 Any ideas? 有任何想法吗?

Global variables are properties of the window object, so you can access them explicitly with window : 全局变量是window对象的属性,因此可以使用window显式访问它们:

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

If you are using global variables, then this is better style, since it is clear what you are doing and assigning to undefined global variables wouldn't throw an error in strict mode. 如果您正在使用全局变量,那么这是更好的样式,因为很清楚您在做什么,并且将其分配给未定义的全局变量在严格模式下不会引发错误。

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

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