0
的困惑爲什麼最終的b
的值不是24而是18?
我認爲,當功能s2
被稱爲最後一次,a
是12
和last
是2
,所以b
應等於12 * 2 = 24
。關於javascript生成器函數
let a = 1, b = 2;
function* foo() {
a++;
yield;
b = b * a;
a = (yield b) + 3;
}
function* bar() {
b--;
yield;
a = (yield 8) + b;
b = a * (yield 2);
}
function step(gen) {
let it = gen();
let last;
return function() {
last = it.next(last).value;
};
}
let s1 = step(foo);
let s2 = step(bar);
s2(); //b=1 last=undefined
s2(); //last=8
s1(); //a=2 last=undefined
s2(); //a=9 last=2
s1(); //b=9 last=9
s1(); //a=12
s2(); //b=24
console.log(a, b);