Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

TypeError: "x" is not a constructor

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

Message

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

Error type

What went wrong?

There was an attempt to use an object or a variable as a constructor, but that objector variable is not a constructor. Seeconstructoror thenew operatorfor more information on what a constructor is.

There are many global objects, likeString orArray, whichare constructable usingnew. However, some global objects are not and theirproperties and methods are static. The following JavaScript standard built-in objectsare 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 constructornew Math();// TypeError: Math is not a constructornew Symbol();// TypeError: Symbol is not a constructorfunction* f() {}const 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 becalledCar, 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;}

Now you can create an object calledmyCar as follows:

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

In Promises

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

This is not legal (thePromise constructor is not being called correctly) and will throw aTypeError: this is not a constructor exception:

js
function fn() {  return new Promise.resolve(true);}

This is legal, but unnecessarily long:

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

Instead, return the static method:

js
function resolveAlways() {  return Promise.resolve(true);}function rejectAlways() {  return Promise.reject(new Error());}

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp