类型错误:"x" 不是构造函数

当尝试使用对象或变量作为构造函数,但该对象或变量不是构造函数时,会发生 JavaScript 异常 "不是构造函数"。

¥The JavaScript exception "is not a constructor" occurs when there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor.

信息

¥Message

TypeError: x is not a constructor (V8-based & Firefox & Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

尝试使用对象或变量作为构造函数,但该对象或变量不是构造函数。有关构造函数的更多信息,请参阅 构造函数new 运算符

¥There was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor. See constructor or the new operator for more information on what a constructor is.

有许多全局对象,例如 StringArray,可以使用 new 构造。然而,一些全局对象不是静态的,它们的属性和方法是静态的。以下 JavaScript 标准内置对象不是构造函数:Math, JSON, Symbol, Reflect, Intl, Atomics.

¥There are many global objects, like String or Array, which are constructable using new. However, some global objects are not and their properties and methods are static. The following JavaScript standard built-in objects are not a constructor: Math, JSON, Symbol, Reflect, Intl, Atomics.

生成器功能 也不能用作构造函数。

¥Generator functions cannot be used as constructors either.

示例

¥Examples

无效案例

¥Invalid cases

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

汽车制造商

¥A car constructor

假设你要为汽车创建一个对象类型。你希望这种类型的对象被称为 Car,并且你希望它具有品牌、型号和年份属性。为此,你需要编写以下函数:

¥Suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

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

现在你可以创建一个名为 mycar 的对象,如下所示:

¥Now you can create an object called mycar as follows:

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

承诺中

¥In Promises

当返回立即解决或立即拒绝的 Promise 时,你不需要创建 new Promise(...) 并对其进行操作。请改用 Promise.resolve()Promise.reject() 静态方法

¥When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a new Promise(...) and act on it. Instead, use the Promise.resolve() or Promise.reject() static methods.

这是不合法的(Promise 构造函数 没有被正确调用)并且会抛出 TypeError: this is not a constructor 异常:

¥This is not legal (the Promise constructor is not being called correctly) and will throw a TypeError: this is not a constructor exception:

js
const fn = () => {
  return new Promise.resolve(true);
};

这是合法的,但不必要的长:

¥This is legal, but unnecessarily long:

js
const fn = () => {
  return new Promise((resolve, reject) => {
    resolve(true);
  });
};

相反,返回静态方法:

¥Instead, return the static method:

js
const resolveAlways = () => {
  return Promise.resolve(true);
};

const rejectAlways = () => {
  return Promise.reject(false);
};

也可以看看

¥See also