我今天在javascript中遇到了yield
关键字,我知道目前在没有升级ECMA 6的浏览器中不支持它。同时,在firefox中,我如何重写以下代码没有yield
if (currentNode) {
yield currentNode;
currentNode = null;
}
没有直接的等价。但是,可以通过返回一个"生成器"对象来伪造它。基本上,将延续代码移动到生成器的next()
中。
考虑MDN上的这个谎言生成器示例:
function fib() {
var i = 0, j = 1;
while (true) {
yield i;
var t = i;
i = j;
j += t;
}
}
var g = fib();
for (var i = 0; i < 10; i++) {
console.log(g.next());
}
并使用假生成器重写:
function fib() {
var i = 0, j = 1;
return {
'next': function () {
var yieldRet = i;
// These haven't occurred before the `yield` in the above generator,
// but it makes it easier to do it in the same order here.
// Just make sure there are no OBSERVABLE side-effects.
var t = i;
i = j;
j += t;
return yieldRet;
}
};
}
var g = fib();
for (var i = 0; i < 10; i++) {
console.log(g.next());
}
现在,随着可观察的可变状态的加入,这确实变得有点棘手;给定的示例仍然可以表示为状态机。注意,每个next
都可以"推进"状态。
var currentNode;
function yield1 () {
var y = { next: st0 };
return y;
function st0 () {
if (currentNode) {
y.next = st1;
return currentNode;
} else {
y.next = stZ;
}
}
function st1 () {
y.next = stZ;
currentNode = null; // observable side-effect!
}
function stZ () {
}
}
var g = yield1();
currentNode = "x";
console.log(g.next()); // "x"
console.log(currentNode); // still "x"
g.next();
console.log(currentNode); // null