TypeError: "x" is not a constructor
JavaScript 異常“不是建構函式”發生在嘗試將物件或變數用作建構函式,但該物件或變數不是建構函式時。
訊息
TypeError: x is not a constructor (V8-based & Firefox & Safari)
錯誤型別
TypeError
哪裡出錯了?
嘗試將物件或變數用作建構函式,但該物件或變數不是建構函式。有關什麼是建構函式,請參閱建構函式或new 運算子。
有許多全域性物件,如String或Array,它們可以使用new構造。然而,有些全域性物件不是,它們的屬性和方法是靜態的。以下 JavaScript 標準內建物件不是建構函式:Math、JSON、Symbol、Reflect、Intl、Atomics。
生成器函式也不能用作建構函式。
示例
無效案例
js
const 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() {}
const obj = new f();
// TypeError: f is not a constructor
汽車建構函式
假設您想為汽車建立一種物件型別。您希望這種物件型別被稱為Car,並且您希望它具有製造廠、型號和年份的屬性。為此,您將編寫以下函式
js
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
現在你可以按如下方式建立名為 myCar 的物件
js
const myCar = new Car("Eagle", "Talon TSi", 1993);
在 Promise 中
當返回一個立即解決或立即拒絕的 Promise 時,您無需建立new Promise(...)並對其進行操作。相反,請使用Promise.resolve()或Promise.reject()靜態方法。
這是非法的(Promise 建構函式未正確呼叫),並將丟擲TypeError: this is not a constructor異常
js
function fn() {
return new Promise.resolve(true);
}
這是合法的,但沒有必要冗長
js
function fn() {
return new Promise((resolve, reject) => {
resolve(true);
});
}
相反,返回靜態方法
js
function resolveAlways() {
return Promise.resolve(true);
}
function rejectAlways() {
return Promise.reject(new Error());
}