是否可以在JavaScript构造函数中分解实例/成员变量? [英] Is it possible to destructure instance/member variables in a JavaScript constructor?
问题描述
是否可以在JavaScript类的构造函数中使用解构分配来分配实例变量,就像如何将其分配给普通变量一样?
Is it possible to use destructuring assignment in a JavaScript class' constructor to assign the instance variables similar to how you can do it to normal variables?
以下示例有效:
var options = {one: 1, two: 2};
var {one, two} = options;
console.log(one) //=> 1
console.log(two) //=> 2
但是我无法执行以下操作:
But I cannot get something like the following to work:
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
推荐答案
执行此操作的方法有多种.第一个仅使用解构,并且将选项的属性分配给 this
上的属性:
There are multiple ways of doing this. The first one uses destructuring only and 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引擎可能会将 {...}
误认为是对象文字或块语句.
The extra parentheses are needed, otherwise the JS engine might mistake the { ... }
for an object literal or a block statement.
第二个使用 Object.assign
和销毁:
The second one uses Object.assign
and destructuring:
class Foo {
constructor(options) {
const {one, two} = options;
Object.assign(this, {one, two});
// Do something else with the other options here
}
}
如果要将选项 all 应用于实例,则可以使用 Object.assign
而不进行破坏:
If you want to apply all your options to the instance, you could use Object.assign
without destructuring:
class Foo {
constructor(options) {
Object.assign(this, options);
}
}
这篇关于是否可以在JavaScript构造函数中分解实例/成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!