Javascript“Not a Constructor”创建对象时发生异常 [英] Javascript "Not a Constructor" Exception while creating objects
本文介绍了Javascript“Not a Constructor”创建对象时发生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我定义一个这样的对象:
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);
但是引发了这个execption:
But this execption is thrown:
Project is not a constructor
可能出错?
推荐答案
代码发布在问题不能产生该错误,因为 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
变量声明总是在代码的其余部分之前进行求值。所以,这也可能是导致问题:
Variable declarations are 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“Not a Constructor”创建对象时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文