GeneratorFunction - JavaScript 编辑
The GeneratorFunction
constructor creates a new generator function object. In JavaScript, every generator function is actually a GeneratorFunction
object.
Note that GeneratorFunction
is not a global object. It could be obtained by evaluating the following code.
Object.getPrototypeOf(function*(){}).constructor
Syntax
new GeneratorFunction ([arg1[, arg2[, ...argN]],] functionBody)
Parameters
arg1, arg2, ... argN
- 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
". functionBody
- A string containing the JavaScript statements comprising the function definition.
Description
generator function
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* 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 function
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.
Invoking the GeneratorFunction
constructor as a function (without using the new
operator) has the same effect as invoking it as a constructor.
Examples
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(iterator.next().value); // 20
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'GeneratorFunction' in that specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论