2

我今天在 javascript 中遇到了yield关键字,我知道目前在未升级 ECMA 6 的浏览器中不支持它。同时在firefox中,我如何在没有的情况下重写以下代码yield

if (currentNode) {
   yield currentNode;
   currentNode = null;
}
4

1 回答 1

3

没有直接的等价物。但是,可以通过返回一个“生成器”对象来伪造它。基本上,延续代码被移动到next()生成器中。

考虑MDN 上的这个 fib-generator 示例

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());
}

现在,添加observable mutable state后,这确实变得有点棘手;给定的示例仍然可以表示为状态机。请注意,每个都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
于 2013-06-05T05:52:22.300 回答