2013-02-15 65 views
0

这是凌乱的东西(不是我的代码,但我坚持它)。函数依赖于全局定义的变量。定义一个函数里面的一个未定义的全局变量

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

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

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

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

但是,如果这个功能现在被称为因为JavaScript评价与定义someGlobalString,该变量设置为undefined,一定可以得到设定为bar

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

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

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

回答

3

全局变量是window对象的属性,所以你可以window明确地访问它们:

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

如果使用全局变量,那么这是更好的方式,因为很明显,你在做什么并分配给未定义的全局变量不会在严格模式下引发错误。

+0

它的作品,doh!以这种方式,它不需要'var'语句。谢谢! – 2013-02-15 10:18:22