修改生成器函数原型

Con*_*ien 5 javascript generator node.js ecmascript-6

TL; DR

我想修改生成器函数实例的原型 - 即从调用a返回的对象function*.


假设我有一个生成器功能:

function* thing(n){
    while(--n>=0) yield n;
}
Run Code Online (Sandbox Code Playgroud)

然后,我做了一个实例:

let four = thing(4);
Run Code Online (Sandbox Code Playgroud)

我想定义一个被调用的生成器原型exhaust,如下所示:

four.exhaust(item => console.log(item));
Run Code Online (Sandbox Code Playgroud)

会产生:

3
2
1
0
Run Code Online (Sandbox Code Playgroud)

我可以通过这样做来破解它:

(function*(){})().constructor.prototype.exhaust = function(callback){
    let ret = this.next();
    while(!ret.done){
        callback(ret.value);
        ret = this.next();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,(function*(){})().constructor.prototype.exhaust看起来非常......哈哈.没有GeneratorFunction我可以轻易编辑的原型......或者在那里?有一个更好的方法吗?

Ber*_*rgi 5

没有GeneratorFunction我可以随时编辑的原型...还是在那里?

不,GeneratorFunction 和Generator实际上没有全局名称。

如果要修改它们,则不要。扩展内建函数是一种反模式。编写静态助手功能的实用程序模块。

(function*(){})().constructor.prototype似乎非常...骇客。有一个更好的方法吗?

我会推荐

const Generator = Object.getPrototypeOf(function* () {});
const GeneratorFunction = Generator.constructor;
Run Code Online (Sandbox Code Playgroud)

那你就可以

Generator.prototype.exhaust = function(…) { … };
Run Code Online (Sandbox Code Playgroud)

如果您确实需要。但是请记住,如果您只是想扩展创建的生成器,function* thing那么您也可以

thing.prototype.exhaust = …;
Run Code Online (Sandbox Code Playgroud)

这可能是一个更好的主意。