ES6 Destructuring assignment with `this`

こ雲淡風輕ζ 提交于 2019-12-08 17:00:22

问题


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.


回答1:


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);



回答2:


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

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

let p = new Person();

console.log(p);


来源:https://stackoverflow.com/questions/47410999/es6-destructuring-assignment-with-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!