簡體   English   中英

ES6生成器和對象解構

[英]ES6 Generators and Object Destructuring

根據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。

數組解構與可迭代/迭代器對象相關聯。 對象解構沒有。 如果你想

const {a, b} = foo

ab拉取值,然后foo需要實際返回foo.afoo.b的值。 因此,您要么只想將屬性存儲在實例本身而不是.props ,要么使用類似的getter

get a() {
    return this.props.a;
}

根據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();

暫無
暫無

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

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