GeneratorFunction 构造函数 creates a new generator 函数 object. In JavaScript, every generator function is actually a GeneratorFunction 对象。

注意: GeneratorFunction is not a global object. It could be obtained by evaluating the following code.



new GeneratorFunction ([arg1[, arg2[, ...argN]],] functionBody)


arg1, arg2, ... arg N
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example " x ", " theValue ", or " a,b ".
A string containing the JavaScript statements comprising the function definition.


generator 函数 objects created with the GeneratorFunction constructor are parsed when the function is created. This is less efficient than declaring a generator function with a function* 表达式 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.

注意: generator 函数 created with the GeneratorFunction 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.

援引 GeneratorFunction 构造函数作为函数 (不使用 new 运算符) 有相同效果若把它作为构造函数进行援引。


Creating a generator function from a GeneratorFunction() constructor

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


ECMAScript (ECMA-262)
The definition of 'GeneratorFunction' in that specification.


更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
GeneratorFunction Chrome 39 Edge 13 Firefox 26 IE No Opera 26 Safari 10 WebView Android 39 Chrome Android 39 Firefox Android 26 Opera Android 26 Safari iOS 10 Samsung Internet Android 4.0 nodejs Yes