Change the prototype of the generator function

TL DR

I want to change the prototype of the generator function instance, that is, the object returned from the function* call.


Say I have a generator function:

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

Then I make an instance of it:

 let four = thing(4); 

I want to define a prototype of generators called exhaust , for example:

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

which will produce:

 3 2 1 0 

I can crack it by doing this:

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

However, (function*(){})().constructor.prototype.exhaust seems very ... brave. No GeneratorFunction whose prototype I can easily edit ... or is there? Is there a better way to do this?

+5
source share
1 answer

No GeneratorFunction whose prototype I can easily edit ... or is there?

No, GeneratorFunction and Generator do not have global names.

If you want to change them ... Do not do this. Extending built-in functions is an antipattern. Write a utility module for static helper functions.

(function*(){})().constructor.prototype seems very ... brave. Is there a better way to do this?

I would recommend

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

then you can do

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

if you really need to. But remember that if you just want to extend the generators created by function* thing , then you can also do

 thing.prototype.exhaust = …; 

which is probably the best idea.

+4
source

All Articles