生成器
Generator 对象由 generator function 返回,它符合 可迭代协议 和 迭代器协议。
¥The Generator object is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.
Generator 是隐藏 Iterator 类的子类。
¥Generator is a subclass of the hidden Iterator class.
Try it
构造函数
¥Constructor
没有与 Generator 构造函数相对应的 JavaScript 实体。Generator 的实例必须从 生成器函数 返回:
¥There's no JavaScript entity that corresponds to the Generator constructor. Instances of Generator must be returned from generator functions:
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator(); // "Generator { }"
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
只有一个隐藏对象,它是由生成器函数创建的所有对象共享的原型对象。该对象通常被风格化为 Generator.prototype,使其看起来像一个类,但它应该更合适地称为 GeneratorFunction.prototype.prototype,因为 GeneratorFunction 是一个实际的 JavaScript 实体。要了解 Generator 实例的原型链,请参阅 GeneratorFunction.prototype.prototype。
¥There's only a hidden object which is the prototype object shared by all objects created by generator functions. This object is often stylized as Generator.prototype to make it look like a class, but it should be more appropriately called GeneratorFunction.prototype.prototype, because GeneratorFunction is an actual JavaScript entity. To understand the prototype chain of Generator instances, see GeneratorFunction.prototype.prototype.
实例属性
¥Instance properties
这些属性在 Generator.prototype 上定义并由所有 Generator 实例共享。
¥These properties are defined on Generator.prototype and shared by all Generator instances.
Generator.prototype.constructor-
创建实例对象的构造函数。对于
Generator实例,初始值为GeneratorFunction.prototype。注意:
Generator对象不存储对创建它们的生成器函数的引用。¥Note:
Generatorobjects do not store a reference to the generator function that created them. Generator.prototype[Symbol.toStringTag]-
[Symbol.toStringTag]属性的初始值为字符串"Generator"。该属性在Object.prototype.toString()中使用。
实例方法
¥Instance methods
还从其父级 Iterator 继承实例方法。
¥Also inherits instance methods from its parent Iterator.
Generator.prototype.next()-
返回
yield表达式产生的值。 Generator.prototype.return()-
就像在当前暂停位置将
return语句插入到生成器主体中一样,该语句完成生成器并允许生成器在与try...finally块组合时执行任何清理任务。 Generator.prototype.throw()-
就像在生成器主体的当前挂起位置插入一条
throw语句一样,它通知生成器错误情况并允许其处理错误,或者执行清理并自行关闭。
示例
无限迭代器
¥An infinite iterator
使用生成器函数,直到需要时才会评估值。因此,生成器允许我们定义潜在无限的数据结构。
¥With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure.
function* infinite() {
let index = 0;
while (true) {
yield index++;
}
}
const generator = infinite(); // "Generator { }"
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// …
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-generator-objects |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also