Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

TypeError: "x" is not a constructor

JavaScript の例外 "is not a constructor" は、オブジェクトや変数をコンストラクターとして使用しようとしたものの、そのオブジェクトや変数がコンストラクターではなかった場合に発生します。

エラーメッセージ

js
TypeError: Object doesn't support this action (Edge)TypeError: "x" is not a constructorTypeError: Math is not a constructorTypeError: JSON is not a constructorTypeError: Symbol is not a constructorTypeError: Reflect is not a constructorTypeError: Intl is not a constructorTypeError: Atomics is not a constructor

エラーの種類

エラーの原因

オブジェクトや変数をコンストラクターとして使おうとしていますが、それらがコンストラクターではありません。コンストラクターとは何かについては、コンストラクターまたはnew 演算子を参照してください。

StringArray のような、new を使用して生成できる数多くのグローバルオブジェクトがあります。しかし、いくつかのグローバルオブジェクトはそうではなく、それらのプロパティやメソッドは静的です。次の JavaScript 標準組み込みオブジェクトのうち、MathJSONSymbolReflectIntlAtomics はコンストラクターではありません。

ジェネレーター関数も、コンストラクターとして使用することはできません。

無効な場合

js
var Car = 1;new Car();// TypeError: Car is not a constructornew Math();// TypeError: Math is not a constructornew Symbol();// TypeError: Symbol is not a constructorfunction* f() {}var obj = new f();// TypeError: f is not a constructor

car コンストラクター

自動車のためのオブジェクト型を作成するとします。このオブジェクト型をCar と呼び、 make, model, year の各プロパティを持つようにしたいとします。これを実現するには、次のような関数を定義します。

js
function Car(make, model, year) {  this.make = make;  this.model = model;  this.year = year;}

次のようにしてmycar というオブジェクトを生成できるようになりました。

js
var mycar = new Car("Eagle", "Talon TSi", 1993);

プロミスの場合

ただちに解決するか拒否されるプロミスを返す場合は、new Promise(...) を生成して操作する必要はありません。

これは正しくなく (Promise コンストラクターが正しく呼び出されません)、TypeError: this is not a constructor 例外が発生します。

js
return new Promise.resolve(true);

代わりに、Promise.resolve() またはPromise.reject()静的メソッドを使用してください。

js
// This is legal, but unnecessarily long:return new Promise((resolve, reject) => { resolve(true); })// Instead, return the static method:return Promise.resolve(true);return Promise.reject(false);

関連情報

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp