javascript 类构造函数中的 ES6 解构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32413025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:13:52  来源:igfitidea点击:

ES6 Destructuring in Class constructor

javascriptecmascript-6destructuring

提问by Lim H.

This may sound ridiculous but bear with me. I wonder if there is support on the language level to destructure object into class properties in constructor, e.g.

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

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}`;
    }
}

回答by

You cannot assign to thisanywhere in the language.

您不能分配到this该语言的任何地方。

One option is to merge into thisor other object:

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

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