Late answering, probably everybody knows about yield
now, but some better documentation has come along.
Adapting an example from "Javascript's Future: Generators" by James Long for the official Harmony standard:
function * foo(x) {
while (true) {
x = x * 2;
yield x;
}
}
"When you call foo, you get back a Generator object which has a next
method."
var g = foo(2);
g.next(); // -> 4
g.next(); // -> 8
g.next(); // -> 16
So yield
is kind of like return
: you get something back. return x
returns the value of x
, but yield x
returns a function, which gives you a method to iterate toward the next value. Useful if you have a potentially memory intensive procedure that you might want to interrupt during the iteration.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…