次のようにオブジェクトを定義しています:
function Project(Attributes, ProjectWidth, ProjectHeight) {
this.ProjectHeight = ProjectHeight;
this.ProjectWidth = ProjectWidth;
this.ProjectScale = this.GetProjectScale();
this.Attributes = Attributes;
this.currentLayout = '';
this.CreateLayoutArray = function()
{....}
}
次に、次のようなインスタンスを作成してみます。
var newProj = new Project(a,b,c);
しかし、この例外がスローされます:
Project is not a constructor
何が間違っているのでしょうか? いろいろグーグルで検索しましたが、まだ何が間違っているのかわかりません。
ベストアンサー1
質問に投稿されたコードは、Project
ユーザー定義関数/有効なコンストラクターではないため、そのエラーを生成できません。
function x(a,b,c){}
new x(1,2,3); // produces no errors
おそらく次のようなことをしたことがあるでしょう:
function Project(a,b,c) {}
Project = {}; // or possibly Project = new Project
new Project(1,2,3); // -> TypeError: Project is not a constructor
変数宣言var
は吊り上げられたしたがって、常にコードの残りの部分より先に評価されます。そのため、これも問題を引き起こす可能性があります。
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
}