javascript - 如何让类方法成为生成器函数?
问题描述
我正在学习 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); }
我知道在我上面的人为示例中,这完全是矫枉过正,但我正在努力学习,所以我必须问:是否有语法可以使第一个选项起作用?
解决方案
推荐阅读
- javascript - .then 在 promise 解决之前触发
- kotlin - 通过 Kotlin 中的反射访问扩展函数(值)
- javascript - LeafletJS 中的交互式地图事件
- javascript - 使用 JQuery 定位下一张卡片
- mongoose - 我想在猫鼬中转换以下 mysql 查询
- javascript - 将两个 JSON 合并为一个
- parameters - 带有 SQL 查询的 Azure 数据工厂集参数
- java - 导出 java ca 证书,以便它可以从 go 中使用
- python - Scipy 中的差异进化与数据
- javascript - 迭代数组并形成另一种格式或数组