简体   繁体   English

ES6 使用“this”进行解构赋值

[英]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. MDN没有说明这种情况。

You can assign to the properties of an existing object by giving aliases and encapsulating the assignment in parentheses ( await codepen ).您可以通过提供别名并将分配封装在括号中( 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() .不需要重复属性键({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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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