ES6在类构造函数中的解构 [英] ES6 Destructuring in Class constructor
本文介绍了ES6在类构造函数中的解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这听起来很荒谬,但请忍受我.我想知道是否在语言级别上支持将对象分解为构造函数中的类属性,例如
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}`;
}
}
推荐答案
您无法在该语言的任何位置分配给this
.
You cannot assign to this
anywhere in the language.
一种选择是合并到this
或其他对象中:
One option is to merge into this
or other object:
constructor(human) {
Object.assign(this, human);
}
这篇关于ES6在类构造函数中的解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文