小编Sev*_*ven的帖子

如何在JavaScript类中编写生成器?

通常,我写这样的代码:

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

但是如何在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`?
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

 class Reply{
      getReply(){
         return function*(msg){
            //...
            return reply;
         }
      }
    }
Run Code Online (Sandbox Code Playgroud)

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

javascript ecmascript-6

25
推荐指数
2
解决办法
2万
查看次数

标签 统计

ecmascript-6 ×1

javascript ×1