理解'产量' javascript中的关键字?

时间:2013-06-05 05:36:47

标签: javascript firefox yield-keyword

我今天在javascript中遇到yield个关键字,我知道目前在非ECMA 6升级的浏览器中不支持它。同时在firefox中,如何在不使用yield

的情况下重写以下代码
if (currentNode) {
   yield currentNode;
   currentNode = null;
}

1 个答案:

答案 0 :(得分:3)

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

考虑这个fib-generator example on 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