使用`this`进行ES6解构分配

san*_*oco 10 javascript destructuring variable-assignment ecmascript-6

以下代码有效.有没有一种更方便的方式,如果可能的话甚至是一个单行程?

const { nextUrl, posts } = await postService.getCommunityPosts(6);
this.communityPosts = posts;
this.nextUrl = nextUrl;
Run Code Online (Sandbox Code Playgroud)

我知道给出了结构化属性别名,但我不认为在这种情况下有帮助.MDN对此案没有任何说明.

Ori*_*ori 15

您可以通过给出别名并将括号括在括号中来分配现有对象的属性(等待代码集).

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

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

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

console.log(target);
Run Code Online (Sandbox Code Playgroud)

  • 请参阅[是否可以在 JavaScript 构造函数中解构实例/成员变量?- Stack Overflow](/sf/ask/2668919151/) 因为括号是必要的。 (2认同)

pio*_*o90 8

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

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

let p = new Person();

console.log(p);
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码可能会回答问题,但提供有关如何和/或为什么解决问题的附加上下文将提高​​答案的长期价值。 (4认同)