2

这可能是重复的,但我不知道如何搜索它。

为什么

var test = test || {};

工作,但是

var test = testing || {};

抛出错误?在定义点两者testtesting都是未定义的。

编辑

抛出的错误是“参考错误:未定义测试”

4

3 回答 3

3

在不存在的意义上未定义的变量与持有该值的变量之间存在差异undefined

test在您的第一个示例中,您声明var这样当=评估右侧的表达式时,变量test存在但具有值undefined

在您的第二个示例中,您根本没有定义testing,因此出现了错误。

编辑:在我看来,也许进一步的解释不会受到伤害。

为简化起见,JavaScript 引擎需要两次遍历代码。第一遍是解析/编译阶段,然后是变量声明而不是赋值。第二遍是实际执行,然后发生分配。这导致了一种通常称为“变量提升”的效果 - 就好像 JS 引擎将声明“提升”到其范围的顶部,但仍会执行分配。

至于这样的代码点:

var test = test || {};

...它基本上是在说“是否test已经存在一个真实的值?如果是这样使用它,否则将它设置为一个新的空对象。”

JS 引擎不介意同一个变量是否在同一范围内多次声明 - 它基本上忽略第二个声明,但不会忽略第二个声明中包含的任何赋值。因此,如果test在其他脚本块中声明,可能在单独的 JS 包含文件中,则相关行仅分配test给自身(假设它具有真实值,其中所有对象都是真实的)。但是如果它没有在其他地方声明,它仍然会作为当前var语句的结果存在,但它会undefined在当前赋值之前,所以||运算符返回右手操作数,{}.

于 2012-11-22T10:54:43.390 回答
1

It's due to the var keyword. Because the variable is declared it also exists albeit with the value undefined. What the || then does is to check for truthiness and when it finds that the object is undefined it gives you a new object to work with.

The latter does the exact same but since you're doing it on "one line" the testing object isn't defined when evaluated and thusly throws the exception.

于 2012-11-22T10:53:04.710 回答
1
var test = test || {};

在这里,test曾经declared但不是defined

但在,

var test = testing || {};

没有任何参考,testing您仍在尝试分配其价值。

第一种情况的相应代码是,

var testing;  // See testing is still undefined
var test = testing || {};
于 2012-11-22T10:56:40.440 回答