ES6 使用 `this` 解构赋值

ES6 Destructuring assignment with `this`

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

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

我知道给解构的属性起别名,但我认为这对这种情况没有帮助。 MDN 没有提到那个案子。

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

const demo = { nextUrl: 'nextUrl', posts: 'posts' };

const target = {}; // replace target with this

({ nextUrl: target.nextUrl, posts: target.communityPosts } = demo);

console.log(target);

function Person() {
  this.obj = {
    firstName: 'Dav',
    lastName: 'P'
  };

  ({firstName: this.firstName, lastName: this.lastName} = this.obj);
}

let p = new Person();

console.log(p);

不需要 ({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);