ES6类构造函数中的解构赋值

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

58

在该语言中,您无法分配给 this

一个选项是将其合并到 this 或其他对象中:

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

3
谢谢。我知道我们不能赋值到这个,但希望有类似的东西。我非常想使用解构语法,因为它有一个明确的模式,即告诉我哪些属性被赋值。不管怎样,感谢您的回答。 - Lim H.
6
也许您需要这个?构造函数({ firstname, lastname }) { Object.assign(this, {firstname, lastename}); this.fullname = ${this.firstname} ${this.lastname}; } - roeland
@r03,你试过那个解决方案了吗?它真的有效吗? - Felipe Quirós
8
这个回答中没有使用“解构”语法。 - vsync
不保存任何输入内容。 - undefined
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接