javascript / latest / global_objects / generatorfunction.html /

GeneratorFunction

In JavaScript, every generator function is actually a GeneratorFunction object. There is no global object with the name GeneratorFunction, but you can create a GeneratorFunction() constructor using the following code:

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

Description

Generator function objects created with a constructor are parsed when the function is created. That is less efficient than declaring a generator function with a function* expression and calling it within your code, because such functions are parsed with the rest of the code.

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

Note: generator functions created with a constructor do not create closures to their creation contexts; they are always created in the global scope.

When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the GeneratorFunction constructor was called.

This is different from using eval with code for a generator function expression.

Invoking a generator function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

Examples

Creating and using a GeneratorFunction() constructor

const GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor;
const g = new GeneratorFunction('a', 'yield a * 2');
const iterator = g(10);
console.log(iterator.next().value); // 20

Specifications

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js
GeneratorFunction
39
13
26
No
26
10
39
39
26
26
10
4.0
1.0
4.0.0
0.12.0

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction