2017-03-17 2 views
-2

생성자 내에서 객체 배열을 작성하려고합니다. 나는 그것이 가능한지 혹은 권할 지 모른다. 하지만 연습을 위해 이것을 만들려고 노력하고 있는데 왜 작동하지 않는지 궁금합니다. 나는 여전히 같은 오류를 받고 있어요, "test"this를 교체하더라도 Uncaught TypeError: Cannot read property 'push' of undefined : 일반 자바 스크립트에서 생성자에서 배열로 푸시

// 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. 
 
}

내가지고있어 오류입니다. 생성자의 바깥이 잘

작업하는 동안 : theList.push(VVD);

왜이 작동하지 않습니다? 그리고 객체를 배열에 푸시하는 더 좋은 방법이 있습니까?

CodePen에 대한 링크

: 당신은 당신의 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); 
+1

'기능 Party'가 * 게양 * 할 일이; 'theList = []'은 그렇지 않습니다. – deceze

답변

2

theList을 정의하기 전에

+1

글쎄 ...'var' 실제로 * 게양 된; '= []'할당은 ... – deceze

+0

파티를 정의하기 전에'Party'를 생성하면 안됩니다. – stackoverfloweth

+0

아, 좋은 구분을 지적합니다. 나는 내 대답을 편집 할 것이다. – gyre

0

http://codepen.io/MichaelVanDenBerg/pen/gmXZej 당신은 새로운 Party를 만들었습니다.

함수 선언 (사용자의 Party 생성자와 유사 함)은 범위의 맨 위로 올라갑니다. 그러나 theList = []과 같은 변수에 대한 지정은 없습니다 (var theList 선언 자체가 올라 갔음에도 불구하고). 따라서, 귀하의 코드는 다음과 같이 해석되고있다 : 생성자가 먼저 호출 될 때 theListundefined 이유

var theList; 

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

// List of objects. 
theList = []; 

당신은 더 명확하게 여기에서 볼 수 있습니다. 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)

관련 문제