ecma6 yield

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 方法,javascript

yield 賦值表達式:在下一次調用 next 時將傳入的值賦給變量,java

若是遇到 return 則迭代執行結束app

 

迭代構造器繼承自 Function , 所以 function 具有的用於修改執行體內的 this 指向 的 call、apply、bind 方法,迭代構造器也都具有,用法與 function 同樣, 另外, 迭代構造器不容許訪問 caller 屬性this

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*  操做會執行迭代操做二凡返回這個對象spa

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 }
相關文章
相關標籤/搜索