参考错误:分配给未声明的变量 "x"

当值被分配给未声明的变量时,仅 JavaScript 严格模式 异常 "分配给未声明的变量" 发生。

¥The JavaScript strict mode-only exception "Assignment to undeclared variable" occurs when the value has been assigned to an undeclared variable.

信息

¥Message

ReferenceError: x is not defined (V8-based)
ReferenceError: assignment to undeclared variable x (Firefox)
ReferenceError: Can't find variable: x (Safari)

错误类型

¥Error type

仅限 严格模式 中的 ReferenceError

¥ReferenceError in strict mode only.

什么地方出了错?

¥What went wrong?

已将值分配给未声明的变量。换句话说,存在一个没有 var 关键字的赋值。声明的变量和未声明的变量之间存在一些差异,这可能会导致意外的结果,这就是 JavaScript 在严格模式下出现错误的原因。

¥A value has been assigned to an undeclared variable. In other words, there was an assignment without the var keyword. There are some differences between declared and undeclared variables, which might lead to unexpected results and that's why JavaScript presents an error in strict mode.

关于声明和未声明的变量需要注意三件事:

¥Three things to note about declared and undeclared variables:

  • 声明的变量受声明它们的执行上下文的约束。未声明的变量始终是全局的。
  • 声明的变量是在执行任何代码之前创建的。未声明的变量在执行分配给它们的代码之前并不存在。
  • 声明的变量是其执行上下文(函数或全局)的不可配置属性。未声明的变量是可配置的(例如可以删除)。

有关更多详细信息和示例,请参阅 var 参考页。

¥For more details and examples, see the var reference page.

有关未声明变量赋值的错误仅发生在 严格模式代码 中。在非严格代码中,它们会被默默地忽略。

¥Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

示例

¥Examples

无效案例

¥Invalid cases

在这种情况下,变量 "bar" 是一个未声明的变量。

¥In this case, the variable "bar" is an undeclared variable.

js
function foo() {
  "use strict";
  bar = true;
}
foo(); // ReferenceError: assignment to undeclared variable bar

有效案例

¥Valid cases

要使 "bar" 成为声明变量,可以在其前面添加 letconstvar 关键字。

¥To make "bar" a declared variable, you can add a let, const, or var keyword in front of it.

js
function foo() {
  "use strict";
  const bar = true;
}
foo();

也可以看看

¥See also