ReferenceError
Baseline 廣泛可用 *
ReferenceError 物件表示在當前作用域中引用了不存在(或尚未初始化)的變數時發生的錯誤。
ReferenceError 是一個 可序列化物件,因此可以使用 structuredClone() 進行克隆,或者透過 postMessage() 在 Worker 之間複製。
ReferenceError 是 Error 的子類。
建構函式
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 |
瀏覽器相容性
載入中…