オブジェクト作成中にJavascriptの「コンストラクタではありません」例外が発生する 質問する

オブジェクト作成中にJavascriptの「コンストラクタではありません」例外が発生する 質問する

次のようにオブジェクトを定義しています:

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
}

おすすめ記事