【问题标题】:Push to array from constructor in plain JavaScript在纯 JavaScript 中从构造函数推送到数组
【发布时间】: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


【解决方案1】:

在您创建theList 数组之前调用您的Party 构造函数。

函数声明(如您的Party 构造函数)被提升到其范围的顶部;但是,对 theList = [] 等变量的赋值不是(即使 var theList 声明本身已被提升)。因此,您的代码被这样解释:

var theList;

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

// List of objects.
theList = [];

你可以在这里更清楚地看到为什么当你的构造函数第一次被调用时theListundefined。尝试重新排序语句,以便在 VVD 之前创建 theList

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

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


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

console.log(theList)

【讨论】:

  • 嗯……var 实际上吊装了; = [] 分配不是...
  • 你不应该在定义Party之前创建Party
  • @stackoverfloweth 这没关系,因为函数声明提升。这是风格问题。
  • 谢谢!也许我仍然做错了什么,但即使我重新排序代码,它仍然无法正常工作。正如你在我的 CodePen 中看到的:codepen.io/MichaelVanDenBerg/pen/gmXZej
  • 您向构造函数 (theList) 添加了不应存在的第三个参数。如果删除它,代码就可以正常工作。
【解决方案2】:

您在定义 theList 之前创建了一个新的 Party

// 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2011-07-07
    • 2012-01-27
    相关资源
    最近更新 更多