TypeError: "x" is not a constructor
メッセージ
TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: JSON is not a constructor TypeError: Symbol is not a constructor TypeError: Reflect is not a constructor TypeError: Intl is not a constructor TypeError: SIMD is not a constructor TypeError: Atomics is not a constructor
エラータイプ
何がうまくいかなかったのか?
オブジェクト、または変数をコンストラクターとして使おうとしていますが、それらがコンストラクターではありません。コンストラクターとは何かについては、コンストラクター か new
演算子を見てください。
String
や Array
のような、new
を使用して生成できる数多くのグローバルオブジェクトがあります。しかし、いくつかのグローバルオブジェクトはそうではなく、 それらのプロパティやメソッドは静的です。次の JavaScript 標準ビルトインオブジェクトは、コンストラクターではありません: Math
と JSON
、Symbol
、Reflect
、Intl
、SIMD
、Atomics
。
function* も、コンストラクターとして使用することはできません。
例
無効なケース
var Car = 1;
new Car();
// TypeError: Car is not a constructor
new Math();
// TypeError: Math is not a constructor
new Symbol();
// TypeError: Symbol is not a constructor
function* f() {};
var obj = new f;
// TypeError: f is not a constructor
car コンストラクター
車のためのオブジェクト型を生成するとします。このオブジェクトの型が car
と呼ばれ、make と model、year プロパティを持つとします。これを行うには、次の関数を定義します:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
次のように mycar
と呼ばれるオブジェクトを生成できます:
var mycar = new Car('Eagle', 'Talon TSi', 1993);
In Promises
When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a new Promise(...) and act on it.
This is not legal (the Promise constructor is not being called correctly) and will throw a TypeError: this is not a constructor
exception:
return new Promise.resolve(true);
Instead, use the Promise.resolve() or Promise.reject() static methods:
// 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);
関連項目
- constructor
new
演算子