【问题标题】:ES6 Destructuring assignment with `this`使用 `this` 的 ES6 解构赋值
【发布时间】:2018-05-04 19:01:43
【问题描述】:

下面的代码有效。有没有更方便的方法,如果可能的话,甚至是单线?

const { nextUrl, posts } = await postService.getCommunityPosts(6);
this.communityPosts = posts;
this.nextUrl = nextUrl;

我知道给解构属性别名,但我认为这在这种情况下没有帮助。 MDN 对此案只字未提。

【问题讨论】:

    标签: javascript ecmascript-6 variable-assignment destructuring


    【解决方案1】:

    您可以通过提供别名并将分配封装在括号中来分配现有对象的属性 (await codepen)。

    const demo = { nextUrl: 'nextUrl', posts: 'posts' };
    
    const target = {}; // replace target with this
    
    ({ nextUrl: target.nextUrl, posts: target.communityPosts } = demo);
    
    console.log(target);

    【讨论】:

    【解决方案2】:

    function Person() {
      this.obj = {
        firstName: 'Dav',
        lastName: 'P'
      };
    
      ({firstName: this.firstName, lastName: this.lastName} = this.obj);
    }
    
    let p = new Person();
    
    console.log(p);

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    【解决方案3】:

    不需要像({key1: this.key1, key2: this.key2} = ... 那样重复的属性键的另一种方法是使用Object.assign()

    class X {
      constructor(properties) {
        ({...this} = properties); // Invalid destructuring assignment target
      }
    }
    
    x = new X({a: 3});
    console.log(x);

    class X {
      constructor(properties) {
        Object.assign(this, properties);
      }
    }
    
    x = new X({a: 3});
    console.log(x);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2019-07-11
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多