ReferenceError

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

* 此特性的某些部分可能存在不同級別的支援。

ReferenceError 物件表示在當前作用域中引用了不存在(或尚未初始化)的變數時發生的錯誤。

ReferenceError 是一個 可序列化物件,因此可以使用 structuredClone() 進行克隆,或者透過 postMessage()Worker 之間複製。

ReferenceErrorError 的子類。

建構函式

ReferenceError()

建立一個新的 ReferenceError 物件。

例項屬性

還繼承了其父級 Error 的例項屬性。.

這些屬性定義在 ReferenceError.prototype 上,並被所有 ReferenceError 例項共享。

ReferenceError.prototype.constructor

建立例項物件的建構函式。對於 ReferenceError 例項,初始值為 ReferenceError 建構函式。

ReferenceError.prototype.name

表示錯誤型別的名稱。對於 ReferenceError.prototype.name,初始值為 "ReferenceError"

例項方法

繼承了其父級 Error 的例項方法。.

示例

捕獲 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
}

建立 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
}

規範

規範
ECMAScript® 2026 語言規範
# sec-native-error-types-used-in-this-standard-referenceerror

瀏覽器相容性

另見