function* statement
The function* declaration (the Function keyword followed by an asterisk) defines a generator (generator) function that returns a generator object.
A generator is a function that you can exit from and then re-enter. The environment of the generator (the bound variable) is saved after each execution and continues to be used the next time it is entered.
Invoking a generator function does not immediately execute its body, but instead returns an iterator (iterator) object for the generator function. When an expression of this iterator next()方法被调用时,生成器函数的主体会被执行直至第一个
yield
, the expression defines the value returned by the iterator, or is yield*
delegated to another generator function. next()方法返回一个对象,该对象有一个
the Value property, which represents产出的值,和一个done属性,表示生成器是否已经产出了它最后的值。
Yield
function* Idmaker () { var index = 0; while (index<3) yield index++;} var Gen = Idmaker (); Console.log (Gen.next (). value); 0console.log (Gen.next (). value); 1console.log (Gen.next (). value); 2console.log (Gen.next (). value); Undefined
yield*
function* Anothergenerator (i) { yield i + 1; Yield i + 2; Yield i + 3;} function* Generator (i) { yield i; yield* Anothergenerator (i); Yield i + 10;} var gen = generator; Console.log (Gen.next (). value); 10console.log (Gen.next (). value); 11console.log (Gen.next (). value); 12console.log (Gen.next (). value); 13console.log (Gen.next (). value); 20
"JavaScript" ES6 new syntax