如何模拟JavaScript产出? [英] How to simulate JavaScript yield?

查看:41
本文介绍了如何模拟JavaScript产出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript 1.7中可用的新机制之一是收益,对生成器和迭代器很有用./p>

(仅我知道)当前仅在Mozilla浏览器中支持此功能.有哪些方法可以在不可用的浏览器中模拟此行为?

解决方案

好吧,您总是可以编写一个外部函数,该函数在闭包中初始化变量,然后返回一个对象,该对象可以完成您想要的任何工作.

  function fakeGenerator(x){var i = 0;返回 {下一个:function(){返回我<X ?(i + = 1):x;}};} 

现在您可以写:

  var gen = fakeGenerator(10); 

,然后一遍又一遍地调用 gen.next().在真实的生成器上模拟"close()"方法的最终"行为是很棘手的,但是您也许可以找到一个接近的地方.

One of the new mechanisms available in JavaScript 1.7 is yield, useful for generators and iterators.

This is currently supported in Mozilla browsers only (that I'm aware of). What are some of the ways to simulate this behavior in browsers where it is not available?

解决方案

Well you could always write an outer function that initializes variables in a closure and then returns an object that does whatever work you want.

function fakeGenerator(x) {
  var i = 0;
  return {
    next: function() {
      return i < x ? (i += 1) : x;
    }
  };
}

Now you can write:

var gen = fakeGenerator(10);

and then call gen.next() over and over again. It'd be tricky to simulate the "finally" behavior of the "close()" method on real generators, but you might be able to get somewhere close.

这篇关于如何模拟JavaScript产出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆