【发布时间】:2017-03-17 20:46:17
【问题描述】:
我正在尝试从构造函数中构建一个对象数组。我不知道这是否可能或可取。但是我正在尝试构建它以进行练习,我想知道为什么它不起作用。
// Variables.
const VVD = new Party("VVD", 33);
// 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.
}
这是我遇到的错误:Uncaught TypeError: Cannot read property 'push' of undefined 即使我将 this 替换为 "test",我仍然会遇到同样的错误。
虽然在构造函数之外,但它工作正常:
theList.push(VVD);
为什么这不起作用?是否有更好、更智能的方式将对象推送到数组?
CodePen 的链接:http://codepen.io/MichaelVanDenBerg/pen/gmXZej
【问题讨论】:
-
function Party恰好被提升;theList = []不是。
标签: javascript arrays object constructor push