ecmascript 6 - How can I write a generator in a JavaScript class? -


usually, write code this:

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

but how can write , use generator in , out of es6 class? tried this:

class reply{     *getreply (msg){         //...         return reply;      }      *otherfun(){         this.getreply();  //`this` seem have no access `getreply`     } } var reply = new reply(); reply.getreply();   //out of class,how can access `getreply`? 

i tried:

 class reply{       getreply(){          return function*(msg){             //...             return reply;          }       }     } 

all of these 2 methods seem wrong answers. how can write generator functions in class correctly?

edit: add more examples.
class definition (almost) correct.the error in instantiation var reply = new reply();. tries redefine variable assigned class name. generator function expected yield something. elaborated little op code show working example.

class reply {    //added test purpose    constructor(...args) {      this.args = args;    }     * getreply(msg) {      (let arg in this.args) {        let reply = msg + this.args[arg];        //generator should yield        yield reply;      }      //next call returns (yields) {done:true,value:undefined}    }     * otherfun() {      yield this.getreply('nice meet '); //yields generator object      yield this.getreply('see '); //yes, can access       //next call yields {done:true, value:undefined}    }     * evenmore() {      yield * this.getreply('i miss '); //yields generator result(s)      yield * this.getreply('i miss more ');    }  }  //now test have  const reply = new reply('peter', 'james', 'john');  //let , var here 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();  }


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -