【发布时间】:2015-12-01 11:53:55
【问题描述】:
这听起来可能很荒谬,但请耐心等待。我想知道语言级别是否支持将对象解构为构造函数中的类属性,例如
class Human {
// normally
constructor({ firstname, lastname }) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = `${this.firstname} ${this.lastname}`;
}
// is this possible?
// it doesn't have to be an assignment for `this`, just something
// to assign a lot of properties in one statement
constructor(human) {
this = { firstname, lastname };
this.fullname = `${this.firstname} ${this.lastname}`;
}
}
【问题讨论】:
-
如果您希望
fullname保留firstname和lastname中的更改,请使用getter developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
@Jan 对,谢谢。抱歉,这是一个不好的例子。我只是想证明,在
firstname和lastname之后,如果有意义的话,还有更多的初始化。 -
this不能分配给 - 在 ES5 中永远不会,在 ES6 中唯一改变其“值”的是super()。但要为其分配属性,请参阅副本。
标签: javascript ecmascript-6 destructuring