【问题标题】:ES6 Destructuring in Class constructor [duplicate]类构造函数中的ES6解构[重复]
【发布时间】: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 保留firstnamelastname 中的更改,请使用getter developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @Jan 对,谢谢。抱歉,这是一个不好的例子。我只是想证明,在firstnamelastname 之后,如果有意义的话,还有更多的初始化。
  • this 不能分配给 - 在 ES5 中永远不会,在 ES6 中唯一改变其“值”的是super()。但要为其分配属性,请参阅副本。

标签: javascript ecmascript-6 destructuring


【解决方案1】:

您不能分配给this 语言中的任何位置。

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

constructor(human) {
  Object.assign(this, human);
}

【讨论】:

  • 干杯。我知道我们不能分配给这个,但希望有类似的东西。我非常热衷于使用解构,因为它有一个清晰的模式,即告诉我正在分配哪些属性。但无论如何,谢谢你的回答。
  • 或者你需要这个?构造函数({名字,姓氏}){ Object.assign(这个,{名字,姓氏}); this.fullname = ${this.firstname} ${this.lastname}; }
  • @r03 你试过那个解决方案吗?它真的有效吗?
  • 为什么不行?
  • 这个答案没有解构..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 2016-05-16
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 2017-04-19
  • 2018-02-03
相关资源
最近更新 更多