简体   繁体   English

Javascript使用未定义的变量时出错

[英]Javascript Error when using undefined variable

Check this interactive Google Chrome console log: 查看此交互式Google Chrome控制台日志:

test_1 = 'ok'
 > "ok"

test_2 = test_2 || 'ok'
 > ReferenceError: test_2 is not defined

var test_3 = test_3 || 'ok'
 > undefined

test_1
 > "ok"

test_2
 > ReferenceError: test_2 is not defined

test_3
 > "ok"

When I call test_1 = 'ok' I leave out the var constructor, but the browser still understands this. 当我调用test_1 = 'ok'我省略了var构造函数,但浏览器仍然理解这一点。 I assume it fills in with the var where I omitted, just like it fills in with semicolons. 我假设它填充了我省略的var ,就像它用分号填充一样。

But for test_2 = test_2 || 'ok' 但是对于test_2 = test_2 || 'ok' test_2 = test_2 || 'ok' I get an error. test_2 = test_2 || 'ok'我得到一个错误。 I know test_2 is not defined but it doesn't keep my next example test_3 from working. 我知道test_2没有定义,但它没有使我的下一个示例test_3无法工作。 For some reason the missing var statement becomes a problem. 由于某种原因,缺少的var语句成为一个问题。

Can somebody explain to me why the interpreter throws an error there? 有人可以向我解释为什么解释器会在那里抛出错误吗?

In short, hoisting. 总之,吊装。

Take the third example, that "works": 以第三个例子为例,“有效”:

var test_3 = test_3 || 'ok'

What JavaScript actually does is the following: JavaScript实际上做的是以下内容:

var test_3;

test_3 = test_3 || 'ok';

Now that test_3 is declared, referring to test_3 simply returns undefined rather than throwing a ReferenceError , so what you're essentially doing is this: 现在宣布test_3 ,引用test_3只返回undefined而不是抛出一个ReferenceError ,所以你基本上做的是:

var test_3;

test_3 = undefined || 'ok';

This isn't true with the second example, as test_2 is never declared. 对于第二个示例,情况并非如此,因为从未声明test_2

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

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