Skip to content
Advertisement

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 an instance like this:

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

but this exception is thrown:

Project is not a constructor

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

Advertisement

Answer

The code as posted in the question cannot generate that error, because Project is not a user-defined function / valid constructor.

function x(a,b,c){}
new x(1,2,3);               // produces no errors

You’ve probably done something like this:

function Project(a,b,c) {}
Project = {};               // or possibly   Project = new Project
new Project(1,2,3);         // -> TypeError: Project is not a constructor

Variable declarations using var are hoisted and thus always evaluated before the rest of the code. So, this can also be causing issues:

function Project(){}
function localTest() {
    new Project(1,2,3); // `Project` points to the local variable,
                        // not the global constructor!

   //...some noise, causing you to forget that the `Project` constructor was used
    var Project = 1;    // Evaluated first
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement