【发布时间】:2016-06-27 18:50:11
【问题描述】:
在我当前的 JS 项目中,我有一个 class,它看起来像这样:
function MyClass() {
this.prop1 = true;
this.prop2 = "Hello World";
this.prop3 = "This is another String.";
this.prop4 = "Just another string here.";
}
我希望能够使用Generator 遍历字符串。我可以通过这样做来实现它:
function* createStringIteratorFromMyClass(myclass) {
yield myclass.prop2;
yield myclass.prop3;
yield myclass.prop4;
}
现在我可以像这样遍历字符串:
for(const str createStringIteratorFromMyClass(...)) {
// access str here
}
这很好用,但我想将createStringIteratorFromMyClass 添加到MyClass 的原型中。
类似这样的:
MyClass.prototype.createStringIterator = function* () {
yield this.prop2;
yield this.prop3;
yield this.prop4;
}
此时我得到错误:
意外的标记“*”。期望在函数之前有一个开头的“(” 参数列表。
如何添加一个函数,该函数将生成器返回到我的类的原型?
【问题讨论】:
标签: javascript constructor iterator prototype generator