簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM