简体   繁体   中英

ES6 Destructuring assignment with `this`

The code below works. Is there a way that is more convenient, if possible even a one-liner?

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

I know about giving destructured properties aliases but I don't think that helps in this case. MDN doesn't say anything about that case.

You can assign to the properties of an existing object by giving aliases and encapsulating the assignment in parentheses ( 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);

An alternative that doesn't require duplicate property keys that ({key1: this.key1, key2: this.key2} = ... does is to use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM