ReferenceError

ReferenceError オブジェクトは、現在のスコープに存在しない(あるいはまだ初期化されていない)変数が参照されたときのエラーを表します。

ReferenceErrorシリアライズ可能オブジェクトなので、 structuredClone() で複製したり、ワーカー間で postMessage() を使用してコピーしたりすることができます。

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); // このエラーのスタック
}

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); // このエラーのスタック
}

仕様書

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

ブラウザーの互換性

BCD tables only load in the browser

関連情報