是否可以在 JavaScript 类的构造函数中使用解构赋值来为实例变量赋值,类似于对普通变量的赋值方式?
以下示例有效:
var options = {one: 1, two: 2};
var {one, two} = options;
console.log(one) //=> 1
console.log(two) //=> 2
但是我无法让类似下面的东西工作:
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
最佳答案
有多种方法可以做到这一点。第一个仅使用解构和 assigns the properties of options to properties on this
:
class Foo {
constructor(options) {
({one: this.one, two: this.two} = options);
// Do something else with the other options here
}
}
需要额外的括号,否则 JS 引擎可能会将 { ... }
误认为是对象字面量或 block 语句。
第二个使用 Object.assign
和解构:
class Foo {
constructor(options) {
const {one, two} = options;
Object.assign(this, {one, two});
// Do something else with the other options here
}
}
如果你想将所有选项应用到实例,你可以使用Object.assign
而不解构:
class Foo {
constructor(options) {
Object.assign(this, options);
}
}
关于javascript - 是否可以在 JavaScript 构造函数中解构实例/成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127416/