I am defining an object like this:
JavaScript
x
12
12
1
function Project(Attributes, ProjectWidth, ProjectHeight) {
2
this.ProjectHeight = ProjectHeight;
3
this.ProjectWidth = ProjectWidth;
4
this.ProjectScale = this.GetProjectScale();
5
this.Attributes = Attributes;
6
7
this.currentLayout = '';
8
9
this.CreateLayoutArray = function()
10
{ .}
11
}
12
I then try to create an instance like this:
JavaScript
1
2
1
var newProj = new Project(a,b,c);
2
but this exception is thrown:
JavaScript
1
2
1
Project is not a constructor
2
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.
JavaScript
1
3
1
function x(a,b,c){}
2
new x(1,2,3); // produces no errors
3
You’ve probably done something like this:
JavaScript
1
4
1
function Project(a,b,c) {}
2
Project = {}; // or possibly Project = new Project
3
new Project(1,2,3); // -> TypeError: Project is not a constructor
4
Variable declarations using var
are hoisted and thus always evaluated before the rest of the code. So, this can also be causing issues:
JavaScript
1
9
1
function Project(){}
2
function localTest() {
3
new Project(1,2,3); // `Project` points to the local variable,
4
// not the global constructor!
5
6
//...some noise, causing you to forget that the `Project` constructor was used
7
var Project = 1; // Evaluated first
8
}
9