javascript實(shí)現(xiàn)yield的方法
沒想到代碼一次測試成功.~~只不過是FF下面,修改一下支持IE了。由于IE不認(rèn)function表達(dá)式.
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.
相關(guān)文章
JavaScript設(shè)置獲取和設(shè)置屬性的方法
這篇文章主要介紹了JavaScript設(shè)置獲取和設(shè)置屬性的方法,學(xué)會使用getAttribute、setAttribute的用法,需要的朋友可以參考下2015-03-03原生javascript實(shí)現(xiàn)圖片無縫滾動效果
這篇文章主要介紹了原生javascript實(shí)現(xiàn)圖片無縫滾動效果的相關(guān)資料,需要的朋友可以參考下2016-02-02基于Web Audio API實(shí)現(xiàn)音頻可視化效果
這篇文章主要介紹了基于Web Audio API實(shí)現(xiàn)音頻可視化效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06