此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
TypeError: "x" is not a constructor
信息
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: SIMD is not a constructorTypeError: Atomics is not a constructor
In this article
错误类型
TypeError哪里出错了?
是因为尝试将不是构造器的对象或者变量来作为构造器使用。参考constructor 或者new operator 来了解什么是构造器。
有很多的全局对象比如String、Array 等等都是可以使用new 操作符的构造器。但是有一些全局对象并不是,且其属性和方法都是静态 的。下面的 JavaScript 标准内置对象都不是构造器:Math,JSON,Symbol,Reflect,Intl,SIMD,Atomics。
Generator functions 也不能作为构造器来使用。
示例
>无效的
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,并且你希望它具有 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);关于 Promises
当返回了一个 immediately-resolved 或者 immediately-rejected Promise 的时候,你根本不需要去创建、操作一个新的 Promise 对象。
这是不合法的(Promise constructor 被错误的调用了)且会抛出一个 错误TypeError: this is not a constructor exception:
js
return new Promise.resolve(true);使用Promise.resolve() 或者Promise.reject() 静态方法来代替:
js
// 这是合法的,但是没必要这么长:return new Promise((resolve, reject) => { resolve(true);});// 用静态方法来代替:return Promise.resolve(true);return Promise.reject(false);