javascript實現(xiàn)yield的方法
更新時間:2013年11月06日 16:43:16 作者:
這篇文章介紹了javascript實現(xiàn)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函數(shù)。
注意一下,如果你需要在coroutine里訪問其他this上下文,需要向iterator傳遞進去, 如 example.
相關(guān)文章
JavaScript設(shè)置獲取和設(shè)置屬性的方法
這篇文章主要介紹了JavaScript設(shè)置獲取和設(shè)置屬性的方法,學會使用getAttribute、setAttribute的用法,需要的朋友可以參考下2015-03-03基于Web Audio API實現(xiàn)音頻可視化效果
這篇文章主要介紹了基于Web Audio API實現(xiàn)音頻可視化效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06