javascript实现yield的方法

  没想到代码一次测试成功.~~只不过是FF下面,修改一下支持IE了。由于IE不认function表达式.

  

复制代码 代码如下:

  var Iterator = function (fn) {

  var coroutine = null;

  var cofn_this = null;

  var yield = function() {

  coroutine.apply(cofn_this, arguments);

  }

  // support IE.

  // NOTE: IE eval("function(){}") does not return a function object.

  eval('fn = ' + fn.toString());

  return function(cofn, cothis){

  coroutine = cofn;

  cofn_this = cothis;

  return fn.apply(this)

  };

  }

  Array.prototype.forEach = new Iterator(function () {

  for (var i = 0; i < this.length; i ++) {

  yield(this[i])

  }

  });

  // example.

  this.display = window.alert;

  var A = [1,2,3,4,5];

  A.forEach(function(it){

  this.display(it)

  }, this);

  其中有一个技巧:

  fn = eval(fn.toString())

  用于将fn中的引用绑定到当前的上下文中,这样fn中的yield才会引用到我们定义的yield函数。

  注意一下,如果你需要在coroutine里访问其他this上下文,需要向iterator传递进去, 如 example.