[javascript] Javascript "Not a Constructor" Exception while creating objects

I am defining an object like this:

function Project(Attributes, ProjectWidth, ProjectHeight)
{
    this.ProjectHeight = ProjectHeight;
    this.ProjectWidth = ProjectWidth;
    this.ProjectScale = this.GetProjectScale();
    this.Attributes = Attributes;

    this.currentLayout = '';

    this.CreateLayoutArray = function()
    {....}
}

I then try to create and instance like this:

var newProj = new Project(a,b,c);

But this execption is thrown:

Project is not a constructor

What could be wrong? I googled around a lot, but still can't figure out what I am doing wrong.

This question is related to javascript object constructor typeerror

The answer is


I've googled around also and found this solution:

You have a variable Project somewhere that is not a function. Then the new operator will complain about it. Try console.log(Project) at the place where you would have used it as a construcotr, and you will find it.


Car.js

class Car {
 getName() {return 'car'};
}
export default Car;

TestFile.js

const object = require('./Car.js');
const instance = new object();

error: TypeError: instance is not a constructor

printing content of object

object = {default: Car}

append default to the require function and it will work as contructor

const object = require('object-fit-images').default;
const instance = new object();
instance.getName();

An additional cause of this can be ES2015 arrow functions. They cannot be used as constructors.

const f = () => {};
new f(); // This throws "f is not a constructor"

I have a class in one file that I'm importing into a test file:

//Vec.js
class Vec {

}

module.exports.Vec = Vec;

Changing

//Vec.test.js
const Vec = require('./Vec');
const myVec = new Vec(); //TypeError: Vec is not a constructor

to

//Vec.test.js
const {Vec} = require('./Vec');
const myVec = new Vec(); //Succeeds!

resolved this error for me.


For me it was the differences between import and require on ES6.

E.g.

// processor.js
class Processor {

}

export default Processor

//index.js
const Processor = require('./processor');
const processor = new Processor() //fails with the error

import Processor from './processor'
const processor = new Processor() // succeeds

To add to @wprl's answer, the ES6 object method shorthand, like the arrow functions, cannot be used as a constructor either.

const o = {
  a: () => {},
  b() {},
  c: function () {}
};

const { a, b, c } = o;

new a(); // throws "a is not a constructor"
new b(); // throws "b is not a constructor"
new c(); // works

Sometimes it is just how you export and import it. For this error message it could be, that the default keyword is missing.

export default SampleClass {}

Where you instantiate it:

import SampleClass from 'path/to/class';
let sampleClass = new SampleClass();

Option 2, with curly braces:

export SampleClass {}
import { SampleClass } from 'path/to/class';
let sampleClass = new SampleClass();

In my case I was using the prototype name as the object name. For e.g.

function proto1()
{}

var proto1 = new proto1();

It was a silly mistake but might be of help to someone like me ;)


I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with

module.exports = NAME_OF_CONSTRUCTOR

will also cause the "Not a constructor" exception.


For my project, the problem turned out to be a circular reference created by the require() calls:

y.js:
var x = require("./x.js");
var y = function() { console.log("result is " + x(); }
module.exports = y;

x.js:
var y = require("./y.js");
var my_y = new y(); // <- TypeError: y is not a constructor
var x = function() { console.log("result is " + my_y; }
module.exports = x;

The reason is that when it is attempting to initialize y, it creates a temporary "y" object (not class, object!) in the dependency system that is somehow not yet a constructor. Then, when x.js is finished being defined, it can continue making y a constructor. Only, x.js has an error in it where it tries to use the non-constructor y.


It is happening because you must have used another variable named "project" in your code. Something like var project = {}

For you to make the code work, change as follows:

var project = {} into var project1 = {}


To add the solution I found to this problem when I had it, I was including a class from another file and the file I tried to instantiate it in gave the "not a constructor" error. Ultimately the issue was a couple unused requires in the other file before the class was defined. I'm not sure why they broke it, but removing them fixed it. Always be sure to check if something might be hiding in between the steps you're thinking about.


In my case I'd forgotten the open and close parantheses at the end of the definition of the function wrapping all of my code in the exported module. I.e. I had:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
);

Instead of:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
)();

The compiler doesn't complain, but the require statement in the importing module doesn't set the variable it's being assigned to, so it's undefined at the point you try to construct it and it will give the TypeError: MyClass is not a constructor error.


I had a similar error and my problem was that the name and case of the variable name and constructor name were identical, which doesn't work since javascript interprets the intended constructor as the newly created variable.

In other words:

function project(name){
    this.name = name;
}

//elsewhere...

//this is no good! name/case are identical so javascript barfs. 
let project = new project('My Project');

Simply changing case or variable name fixes the problem, though:

//with a capital 'P'
function Project(name){
    this.name = name;
}

//elsewhere...

//works! class name/case is dissimilar to variable name
let project = new Project('My Project');

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to constructor

Two constructors Class constructor type in typescript? ReactJS: Warning: setState(...): Cannot update during an existing state transition Inheritance with base class constructor with parameters What is the difference between using constructor vs getInitialState in React / React Native? Getting error: ISO C++ forbids declaration of with no type undefined reference to 'vtable for class' constructor Call asynchronous method in constructor? Purpose of a constructor in Java? __init__() missing 1 required positional argument

Examples related to typeerror

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Python TypeError must be str not int Uncaught TypeError: (intermediate value)(...) is not a function Slick Carousel Uncaught TypeError: $(...).slick is not a function Javascript Uncaught TypeError: Cannot read property '0' of undefined JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element' TypeError: 'list' object cannot be interpreted as an integer TypeError: unsupported operand type(s) for -: 'list' and 'list' I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer" Python sum() function with list parameter