생성자 내에서 객체 배열을 작성하려고합니다. 나는 그것이 가능한지 혹은 권할 지 모른다. 하지만 연습을 위해 이것을 만들려고 노력하고 있는데 왜 작동하지 않는지 궁금합니다. 나는 여전히 같은 오류를 받고 있어요, "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);
'기능 Party'가 * 게양 * 할 일이; 'theList = []'은 그렇지 않습니다. – deceze