这可能听起来有些荒谬,但请耐心听我说。我想知道在语言层面上是否支持将对象解构为类属性并在构造函数中使用,例如:
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。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/get - Janfirstname
和lastname
之后还有更多的初始化,如果这样说可以理解的话。 - Lim H.this
赋值,而在 ES6 中唯一能够改变其“值”的是super()
。但是,如果要给它赋属性,请参见重复内容。 - Bergi