简体   繁体   English

Javascript变量范围未定义

[英]Javascript variable scope undefined

I want to define a variable to default value if not already defined but found a strange issue. 我想将变量定义为默认值(如果尚未定义)但发现了一个奇怪的问题。

var x = x || {} var x = x || {} works whereas x = x || {} var x = x || {}有效,而x = x || {} x = x || {} gives an error. x = x || {}给出错误。

Output from firebug. 萤火虫的输出。

>>> a = a || {};
ReferenceError: a is not defined
[Break On This Error]   
a = a || {};
with(_... {}; }; (line 2)
>>> var b = b || {};
undefined

>>> b;
Object {}
>>> a;
ReferenceError: a is not defined
[Break On This Error]   

why does the first one give error while the second seems to go through. 为什么第一个给出错误,而第二个似乎通过。

Just use var . 只需使用var Except for a bug on old IE versions, adding the var saves you an error message and makes it clear that you're not assuming it is declared elsewhere. 除了旧IE版本的错误之外,添加var您保存一条错误消息,并明确表示您并未假设它已在其他地方声明。

On those old versions of IE, 在那些旧版本的IE上,

x = (typeof x !== 'undefined' && x) || {}

a typeof check prevents the "undeclared variable" error. typeof检查可防止“未声明的变量”错误。

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

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