是否可以在JavaScript类的构造函数中使用解构赋值来分配实例变量,类似于如何对常规变量执行此操作?
以下示例有效:
var options = {one: 1, two: 2};
var {one, two} = options;
console.log(one) //=> 1
console.log(two) //=> 2
Run Code Online (Sandbox Code Playgroud)
但我不能得到类似以下的东西:
class Foo {
constructor(options) {
{this.one, this.two} = options;
// This doesn't parse correctly and wrapping in parentheses doesn't help
}
}
var foo = new Foo({one: 1, two: 2});
console.log(foo.one) //=> I want this to output 1
console.log(foo.two) //=> I want this to output 2
Run Code Online (Sandbox Code Playgroud)