繁体   English   中英

修改生成器函数原型

[英]Modifying generator function prototype

TL; DR

我想修改生成器函数实例的原型,也就是从调用function*返回的对象。


假设我有一个生成器函数:

function* thing(n){
    while(--n>=0) yield n;
}

然后,我创建一个实例:

let four = thing(4);

我想定义一个称为exhaust的生成器原型,如下所示:

four.exhaust(item => console.log(item));

会产生:

3
2
1
0

我可以这样做:

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

但是, (function*(){})().constructor.prototype.exhaust似乎非常...骇人听闻。 没有可以轻松编辑其原型的GeneratorFunction ...或者存在吗? 有一个更好的方法吗?

没有可以轻松编辑其原型的GeneratorFunction ...或者存在吗?

不, GeneratorFunctionGenerator实际上没有全局名称。

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

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

我会推荐

const Generator = Object.getPrototypeOf(function* () {});
const GeneratorFunction = Generator.constructor;

那你就可以

Generator.prototype.exhaust = function(…) { … };

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

thing.prototype.exhaust = …;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM