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

时间:2017-11-21 10:38:28

标签: javascript ecmascript-6 variable-assignment destructuring

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

const { nextUrl, posts } = await postService.getCommunityPosts(6);
this.communityPosts = posts;
this.nextUrl = nextUrl;

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

3 个答案:

答案 0 :(得分:11)

您可以通过给出别名并将括号括在括号中来await codepen来分配现有对象的属性。



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

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

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

console.log(target);




答案 1 :(得分:3)

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

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

let p = new Person();

console.log(p);

答案 2 :(得分:1)

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

相关问题