2017-03-17 3 views
-2

私はコンストラクタ内からオブジェクトの配列を構築しようとしています。私はそれが可能であるか、または推奨されているかわからない。しかし、私は練習のためにこれを構築しようとしています、なぜそれが動作していないのだろうか。コンストラクタから単純なJavaScriptで配列にプッシュ

// Variables. 
 
const VVD = new Party("VVD", 33); 
 

 
// List of objects. 
 
var theList = []; 
 

 
// Party constructor. 
 
function Party(name, seats) { 
 
\t this.name = name; 
 
\t this.seats = seats; 
 
\t //theList.push(this); // This isn't working. 
 
\t this.pushToTheList = function() { 
 
\t \t theList.push(this); 
 
\t } 
 
\t this.pushToTheList(); // And neither is this. 
 
}

これは私が取得していますエラーです:Uncaught TypeError: Cannot read property 'push' of undefinedを私は"test"thisを交換する場合でも、私はまだ同じエラーを取得しています。

コンストラクタの外で、これは正常に動作している間: theList.push(VVD);

をなぜこの作業ではないでしょうか?オブジェクトを配列にプッシュする、より良い、スマートな方法がありますか?

CodePenへのリンク:http://codepen.io/MichaelVanDenBerg/pen/gmXZej

+1

'関数Party'は*掲揚*ことを起こります。 'theList = []'はそうではありません。 – deceze

答えて

2

を定義した前に新しいPartyを作成しました。

Partyコンストラクタのような)関数宣言は、スコープの先頭に持ち上げられます。しかし、theList = []のような変数への代入は(var theList宣言自体が吊り上げられていても)行われません。このように、あなたのコードは次のように解釈されている:

var theList; 

// Variables. 
const VVD = new Party("VVD", 33); 

// List of objects. 
theList = []; 

theListがあなたのコンストラクタが最初に呼び出されundefinedである理由あなたがここにもっとはっきりと見ることができます。 theListVVDする前に作成されるように、文を並べ替えてみてください。

// List of objects. 
 
var theList = []; 
 

 
// Variables. 
 
const VVD = new Party("VVD", 33); 
 

 

 
// Party constructor. 
 
function Party(name, seats) { 
 
\t this.name = name; 
 
\t this.seats = seats; 
 
\t //theList.push(this); // This works 
 
\t this.pushToTheList = function() { 
 
\t \t theList.push(this); 
 
\t } 
 
\t this.pushToTheList(); // And so does this. 
 
} 
 

 
console.log(theList)

+1

まあ...実際には 'var'は*ホイストされています。 '= []'の割り当ては... – deceze

+0

'Party'を定義する前に' Party'を作成すべきではありません。 – stackoverfloweth

+0

ああ、良い点を指摘してください。私は私の答えを編集します。 – gyre

0

あなたがあなたのtheList配列を作成前に、あなたのPartyコンストラクタが呼び出されているtheList

// List of objects. 
var theList = []; 

// Party constructor. 
function Party(name, seats) { 
    this.name = name; 
    this.seats = seats; 
    //theList.push(this); // This isn't working. 
    this.pushToTheList = function() { 
     theList.push(this); 
    } 
    this.pushToTheList(); // And neither is this. 
} 

// Variables. 
const VVD = new Party("VVD", 33); 
関連する問題