當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript实现yield
生活随笔
收集整理的這篇文章主要介紹了
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.
轉載于:https://www.cnblogs.com/hackwaly/archive/2008/07/27/1252617.html
總結
以上是生活随笔為你收集整理的javascript实现yield的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CaseStudy(showcase)界
- 下一篇: php 中调用 require incl