首页 > 解决方案 > 如何让类方法成为生成器函数?

问题描述

我正在学习 ES6 生成器函数以及类。我正在尝试将它们结合起来,但不知道是否可以,以及如何。这是我正在尝试做的事情:

class Container {
  constructor(names) {
    this._names = names;
  }
  
  // Won't work:
  //itemsWith*(part) {
  //  for (const name of this._names) {
  //    if (name.includes(part)) yield name;
  //  }
  //}
  
  // Workaround:
  itemsWithPartGeneratorFunc(part) {
    const capturedNames = this._names;
    function* itemsWith() {
      for (const name of capturedNames) {
        if (name.includes(part)) yield name;
      }
    }    
    return itemsWith;
  }
}

const group = new Container(['blue dragon', 'red tiger', 'green tiger']);

// Won't work:
// for (const name of group.itemsWith('tiger')) { console.log(name); }

// Workaround:
for (const name of group.itemsWithPartGeneratorFunc('tiger')()) { console.log(name); }

我知道在我上面的人为示例中,这完全是矫枉过正,但我​​正在努力学习,所以我必须问:是否有语法可以使第一个选项起作用?

标签: javascriptecmascript-6es6-class

解决方案


推荐阅读