Aar*_*ron 19 javascript destructuring variable-assignment
是否可以在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)
nil*_*ils 26
有多种方法可以做到这一点.第一个仅使用解构并将选项的属性分配给以下属性this:
class Foo {
constructor(options) {
({one: this.one, two: this.two} = options);
// Do something else with the other options here
}
}
Run Code Online (Sandbox Code Playgroud)
需要额外的括号,否则JS引擎可能会误认为{ ... }是对象文字或块语句.
第二个使用Object.assign和解构:
class Foo {
constructor(options) {
const {one, two} = options;
Object.assign(this, {one, two});
// Do something else with the other options here
}
}
Run Code Online (Sandbox Code Playgroud)
如果要将所有选项应用于实例,则可以在Object.assign不进行解构的情况下使用:
class Foo {
constructor(options) {
Object.assign(this, options);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1889 次 |
| 最近记录: |