通常,我写这样的代码:

//definition
exports.getReply = function * (msg){
    //...
    return reply;
}
//usage
var msg = yield getReply ('hello');

但是如何在es6类中编写和使用生成器?我尝试了这个:
class Reply{
    *getReply (msg){
        //...
        return reply;
    }
     *otherFun(){
        this.getReply();  //`this` seem to have no access to `getReply`
    }
}
var Reply = new Reply();
Reply.getReply();   //out of class,how can I get access to `getReply`?

我也尝试过:
 class Reply{
      getReply(){
         return function*(msg){
            //...
            return reply;
         }
      }
    }

这两种方法似乎都是错误的答案。那么如何在类中正确编写生成器函数呢?

最佳答案

编辑:添加更多示例。
您的class定义(几乎)是正确的。错误是在实例化var Reply = new Reply();中。这将尝试重新定义分配给类名称的变量。此外,generator函数还需要对yield进行编码。我详细说明了一些OP代码以显示工作示例。

class Reply {
  //added for test purpose
  constructor(...args) {
    this.args = args;
  }
  * getReply(msg) {
      for (let arg in this.args) {
        let reply = msg + this.args[arg];
        //generator should yield something
        yield reply;
      }
      //next call returns (yields) {done:true,value:undefined}
  }
  * otherFun() {
      yield this.getReply('Nice to meet you '); //yields Generator object
      yield this.getReply('See you '); //Yes, this can access
      //next call yields {done:true, value:undefined}
  }
  * evenMore() {
      yield* this.getReply('I miss you '); //yields generator result(s)
      yield* this.getReply('I miss you even more ');
  }
}
//now test what we have
const reply = new Reply('Peter', 'James', 'John');
//let and var here are interchangeable because of Global scope
var r = reply.getReply('Hello ');
var msg = r.next(); //{done:false,value:"..."}
while (!msg.done) {
  console.log(msg.value);
  msg = r.next();
}
var other = reply.otherFun();
var o = other.next(); //{done:false,value:Generator}
while (!o.done) {
  let gen = o.value;
  msg = gen.next();
  while (!msg.done) {
    console.log(msg.value);
    msg = gen.next();
  }
  o = other.next();
}
var more = reply.evenMore();
msg = more.next();
while (!msg.done) {
  console.log(msg.value);
  msg = more.next();
}
//update of 1/12/2019
//more examples
for (let r of reply.getReply('for ')) {
  console.log(r);
}
for (let r of reply.evenMore()) {
  console.log(r);
}
//note that the following doesn't work because of lack of star (*) inside the generator function
for (let r of reply.otherFun()) {
  console.log(r);
}


更新2019年1月12日

正如@BugBuddy所建议的那样,for..of循环看起来更好(但并非在所有情况下都有效)。查看摘要中的更新行。

10-08 09:05
查看更多