ES6生成器和对象解构

时间:2017-08-31 17:20:31

标签: javascript ecmascript-6

根据ES6,可以使用从自定义生成器返回的数组解构。然而现在我无法通过简单的对象解构来找到相同的方法,因为我认为这应该有效(使用Babel和Polyfill):

class Test {
  constructor () { this.props = {a: 1, b: 2}; }

  *[Symbol.iterator]() { yield* this.props; }
}

const {a, b} = new Test();

这实际上应该不行吗?因为它总是简单地为a和b返回undefined。

2 个答案:

答案 0 :(得分:2)

数组解构与可迭代/迭代器对象相关联。对象解构没有。如果你想要

const {a, b} = foo

要提取ab的值,然后foo需要实际返回foo.afoo.b的值。因此,您要么只想将属性存储在实例本身而不是.props,要么使用像

这样的getter
get a() {
    return this.props.a;
}

答案 1 :(得分:1)

  

根据ES6,可以使用从自定义生成器返回的数组解构。

  

这应该有用吗?

不 - 你这里没有使用数组。通过对对象文字进行解构,永远不会调用迭代器,如果是,它会抛出一个关于this.props对象不可迭代的异常。

现在我无法通过简单的对象解构来找到相同的方法,因为我认为这应该有效(使用Babel和Polyfill):

class Test {
  constructor () {
    this.propA = 1;
    this.propB = 2;
    this.propArr = [];
  }
  *[Symbol.iterator]() {
    yield this.propA; // yield the single value
    yield this.propB; // yield another value
    yield* this.propArr; // yield every from an iterable
  }
}

const [a, b] = new Test();
//    ^    ^ *array* destructuring!

对象解构可以在这里用作

const {propA: a, propB: b} = new Test();
相关问题