生成器对象是由一个 generator function 返回的,并且它符合可迭代协议和迭代器协议。
function* gen() { yield 1; yield 2; yield 3; } let g = gen(); // "Generator { }"
Generator.prototype.next()
yield
表达式生成的值。Generator.prototype.return()
Generator.prototype.throw()
function* idMaker(){ let index = 0; while(true) yield index++; } let gen = idMaker(); // "Generator { }" console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 // ...
Firefox (SpiderMonkey) 在 JavaScript 1.7 中也实现了一个较早版本的生成器,其中函数声明中的星号(*)不是必需的 (只需在函数体中使用yield
关键字)。但是,旧式生成器已弃用。不要使用它们;他们将被删除 (bug 1083482)。
Generator.prototype.next()
yield
表达式产生的值. 与ES2015 生成器对象的next()方法对应.Generator.prototype.close()
next()函数时将会抛出
StopIteration
错误. 与ES2015 生成器对象的return()方法对应..Generator.prototype.send()
yield
表达式返回, 并且返回下一个 yield
表达式产生的值. send(x)
对应于ES2015生成器对象中的 next(x)
Generator.
prototype.
throw()
function fibonacci() { var a = yield 1; yield a * 2; } var it = fibonacci(); console.log(it); // "Generator { }" console.log(it.next()); // 1 console.log(it.send(10)); // 20 console.log(it.close()); // undefined console.log(it.next()); // throws StopIteration (as the generator is now closed)
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) Generator objects |
Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) Generator objects |
Draft |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 39.0 | (Yes) | 未实现 | 未实现 | 未实现 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 未实现 | 39.0 | (Yes) | 未实现 | 未实现 | 未实现 |
StopIteration