沒想到代碼一次測試成功.~~只不過是FF下面,修改一下支持IE了。由于IE不認(rèn)function表達(dá)式.
復(fù)制代碼 代碼如下:
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中的引用綁定到當(dāng)前的上下文中,這樣fn中的yield才會引用到我們定義的yield函數(shù)。
注意一下,如果你需要在coroutine里訪問其他this上下文,需要向iterator傳遞進(jìn)去, 如 example.
新聞熱點(diǎn)
疑難解答
圖片精選