【发布时间】:2018-12-19 13:34:15
【问题描述】:
在我的应用中,我使用来自 API 请求的数据创建了几个不同的对象,如下所示:
const newRelationship = new Relationship(
data.id,
data.account_id,
data.name,
data.description,
data.created_at,
data.created_by,
data.deleted_at,
data.deleted_by,
data.updated_at,
data.updated_by,
);
这感觉有点麻烦。有没有更好的(一行)方法来做到这一点,而不是像这样手动写出所有参数?
我希望如下所示,但我还没有 100% 了解传播/解构。
const newRelationship = new Relationship(...data);
我的关系构造函数如下:
constructor(id, accountId, name, description, createdAt, createdBy, updatedAt, updatedBy, deletedAt, deletedBy) {
this.id = id || '';
this.accountId = accountId || '';
this.name = name || '';
this.description = description || '';
this.createdAt = createdAt || '';
this.createdBy = createdBy || '';
this.deletedAt = deletedAt || '';
this.deletedBy = deletedBy || '';
this.updatedAt = updatedAt || '';
this.updatedBy = updatedBy || '';
}
【问题讨论】:
-
但传播不会按照这个顺序,最好改变关系的工作方式
-
请发布您的关系构造函数。它期待一个对象吗?
-
你也可以使用named parameters
-
为什么不将
data对象本身传递给构造然后使用它?!!
标签: javascript es6-class destructuring spread-syntax