TypeError: "x" is not a constructor - 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: Object doesn't support this action (Edge)
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: Atomics is not a constructor

Error type

TypeError

What went wrong?

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.

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

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

A car constructor

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:

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

Now you can create an object called mycar as follows:

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);

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:110 次

字数:5152

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文