I didn't expect the code to test successfully. ~ ~ is only ff below, modified to support IE. Because IE does not recognize function expressions.
Copy Code code as follows:
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);
One of the tips is:
fn = eval (fn.tostring ())
Used to bind a reference in FN to the current context so that the yield in FN references the yield function we defined.
Note that if you need to access the other this context in coroutine, you need to pass it in to iterator, such as example.