我试图将一个对象分解为如下属性;
let example = {name: 'Fred', age:20}
const {name, age} = example;
但是,我希望它能对它所在班级的这个。name和这个。age做些什么。 像;
class Test = {
name: ''
age: null
constructor(example) {
{this.name, this.age} = example;
}
}
这可能吗?
可以使用析构来为对象赋值。 绝对不推荐。 您可以看到原因:
null
class Test {
name = ''
age = null
constructor(example) {
({ name: this.name, age: this.age } = example) // <- dont't forget the parenthesis
}
}
console.log(
new Test({ name: 'name', age: 10 })
)