[英]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.