function * generator(k){ console.log('begin'); var x = yield k; console.log('x:',x); var y = yield x+k; console.log('y:',y); return x+y+k; } var o = generator(1); var r = o.next(); console.log('1:'+r.value, 'done:'+r.done); r = o.next(3); console.log('2:'+r.value,'done:'+r.done); r = o.next(5); console.log('3:'+r.value,'done:'+r.done); //log begin 1:1 done:false x: 3 2:4 done:false y: 5 3:9 done:true =========================================================================== function * generator(k){ console.log('begin'); var x = yield k; console.log('x:',x); return 'end'; var y = yield x+k; console.log('y:',y); return x+y+k; } var o = generator(1); var r = o.next(); console.log('1:'+r.value,'done:'+r.done); r = o.next(3); console.log('2:'+r.value,'done:'+r.done); r = o.next(5); console.log('3:'+r.value,'done:'+r.done); //log begin 1:1 done:false x: 3 2:end done:true 3:undefined done:true
迭代构造器可以接受初值,在构造时传入而非首次调用 next 时,
yield 后面的值被返回,后继代码暂时中断,直到调用 next 方法,
yield 赋值表达式:在下一次调用 next 时将传入的值赋給变量,
如果遇到 return 则迭代执行结束
迭代构造器继承自 Function , 因此 function 具备的用于修改执行体内的 this 指向 的 call、apply、bind 方法,迭代构造器也都具备,用法与 function 一样, 另外, 迭代构造器不允许访问 caller 属性
function fun(){ var g = function *(k){ console.log(arguments[0],arguments.length,arguments.callee) console.log(this); var x = yield 123; return x; } var o = g.call(({a:123,b:456}),888) o.next() o.next(999) } fun() //log 888 1 function g(k) Object {a: 123, b: 456}
使用 yield* 表达式 执行可迭代对象:如果过yield* 后面的表达式是一个可迭代对象,则 yield* 操作会执行迭代操作而返回这个可迭代对象迭代完毕的结果。
function* g1() { yield 2; yield 3; yield 4; } function* g2() { yield 1; yield* g1(); yield 5; } var iterator = g2(); console.log(iterator.next()); // { value: 1, done: false } console.log(iterator.next()); // { value: 2, done: false } console.log(iterator.next()); // { value: 3, done: false } console.log(iterator.next()); // { value: 4, done: false } console.log(iterator.next()); // { value: 5, done: false } console.log(iterator.next()); // { value: undefined, done: true }