Javascript 在函数中定义未定义的全局变量
这是一堆乱七八糟的东西(不是我的代码,但我坚持这样做)。函数依赖于全局定义的变量Javascript 在函数中定义未定义的全局变量,javascript,variables,casting,scope,operator-precedence,Javascript,Variables,Casting,Scope,Operator Precedence,这是一堆乱七八糟的东西(不是我的代码,但我坚持这样做)。函数依赖于全局定义的变量 function variableIssues(){ alert(someGlobalString); // alerts "foo" } 有时这个全局定义的变量是,未定义的。在这种情况下,我们希望将其转换为进一步处理。该函数已修改 function variableIssues(){ alert(someGlobalString); // undefined if (!someGlo
function variableIssues(){
alert(someGlobalString); // alerts "foo"
}
有时这个全局定义的变量是,未定义的
。在这种情况下,我们希望将其转换为进一步处理。该函数已修改
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";
}
}
我想得到一些关于如何处理
未定义的
全局变量的建议。有什么想法吗?全局变量是窗口
对象的属性,因此您可以使用窗口
显式访问它们:
if (!window.someGlobalString) {
// depending on possible values, you might want:
// if (typeof window.someGlobalString === 'undefined')
window.someGlobalString = "bar";
}
如果您使用的是全局变量,那么这是一种更好的样式,因为很明显,您正在执行的操作和分配给未定义的全局变量不会在严格模式下引发错误。全局变量是
窗口
对象的属性,因此您可以使用窗口
显式访问它们:
if (!window.someGlobalString) {
// depending on possible values, you might want:
// if (typeof window.someGlobalString === 'undefined')
window.someGlobalString = "bar";
}
如果您使用的是全局变量,那么这是一种更好的样式,因为很清楚您在做什么,并且分配给未定义的全局变量不会在严格模式下抛出错误。它可以工作,doh!以这种方式,它不需要
var
语句。谢谢它起作用了,doh!以这种方式,它不需要var
语句。谢谢