Javascript“不是构造函数"创建对象时出现异常 [英] Javascript "Not a Constructor" Exception while creating objects
本文介绍了Javascript“不是构造函数"创建对象时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在定义一个这样的对象:
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);
但是抛出了这个异常:
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.
推荐答案
问题中发布的代码无法生成该错误,因为 Project
不是用户定义的函数/有效的构造函数.
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
使用 var
的变量声明是提升,因此总是在其余代码之前评估.因此,这也可能导致问题:
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
}
这篇关于Javascript“不是构造函数"创建对象时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文