【发布时间】:2018-07-10 20:12:22
【问题描述】:
在编写 ES6 类时,您可以在构造函数中使用解构,以便更轻松地使用默认选项:
class Person {
constructor({
name = "Johnny Cash",
origin = "American",
profession = "singer"
} = {}) {
this.name = name;
this.origin = origin;
this.profession = profession;
}
toString() {
return `${this.name} is an ${this.origin} ${this.profession}`;
}
}
这允许你做这样的事情:
const person = new Person();
console.log(person.toString());
// Returns 'Johnny Cash is an American singer'
const nina = new Person({
name : "Nina Simone"
})
console.log(nina.toString());
// Returns 'Nina Simone is an American singer'
但是,您需要重复构造函数中的参数以将它们分配给类实例。我已经发现你可以这样做以减少冗长:
Object.assign(this, { name, origin, profession });
但是您仍然需要重复这三个变量。有什么方法可以在不重复变量的情况下使赋值更短?
【问题讨论】:
标签: javascript ecmascript-6 es6-class