类构造函数中的ES6解构

Lim*_* H. 21 javascript destructuring ecmascript-6

这可能听起来很荒谬,但请耐心等待.我想知道在语言层面是否支持将对象解构为构造函数中的类属性,例如

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}`;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 33

您无法分配到this该语言的任何位置.

一种选择是合并到this其他对象:

constructor(human) {
  Object.assign(this, human);
}
Run Code Online (Sandbox Code Playgroud)

  • 或许你需要这个?构造函数({firstname,lastname}){Object.assign(this,{firstname,lastename}); this.fullname =`$ {this.firstname} $ {this.lastname}`; } (6认同)
  • 这个答案中没有“破坏性”的内容。 (4认同)
  • 干杯.我知道我们不能指定这个,但希望有类似的东西.我非常热衷于使用解构,因为它有一个清晰的架构,即告诉我正在分配哪些属性.但无论如何,谢谢你的回答. (2认同)