ReferenceError

当引用当前作用域中不存在(或尚未初始化)的变量时,ReferenceError 对象表示错误。

¥The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.

ReferenceErrorserializable object,因此可以使用 structuredClone() 进行克隆,或者使用 postMessage()工人 之间进行复制。

¥ReferenceError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().

ReferenceErrorError 的子类。

¥ReferenceError is a subclass of Error.

构造函数

¥Constructor

ReferenceError()

创建一个新的 ReferenceError 对象。

实例属性

¥Instance properties

还从其父级 Error 继承实例属性。

¥Also inherits instance properties from its parent Error.

这些属性在 ReferenceError.prototype 上定义并由所有 ReferenceError 实例共享。

¥These properties are defined on ReferenceError.prototype and shared by all ReferenceError instances.

ReferenceError.prototype.constructor

创建实例对象的构造函数。对于 ReferenceError 实例,初始值为 ReferenceError 构造函数。

ReferenceError.prototype.name

表示错误类型的名称。对于 ReferenceError.prototype.name,初始值为 "ReferenceError"

实例方法

¥Instance methods

从其父级 Error 继承实例方法。

¥Inherits instance methods from its parent Error.

示例

¥Examples

捕获引用错误

¥Catching a ReferenceError

js
try {
  let a = undefinedVariable;
} catch (e) {
  console.log(e instanceof ReferenceError); // true
  console.log(e.message); // "undefinedVariable is not defined"
  console.log(e.name); // "ReferenceError"
  console.log(e.stack); // Stack of the error
}

创建引用错误

¥Creating a ReferenceError

js
try {
  throw new ReferenceError("Hello");
} catch (e) {
  console.log(e instanceof ReferenceError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "ReferenceError"
  console.log(e.stack); // Stack of the error
}

规范

Specification
ECMAScript Language Specification
# sec-native-error-types-used-in-this-standard-referenceerror

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also