虚拟机,编译原理,应用框架

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.

posted on 2008-07-27 16:12  文宇祥  阅读(2892)  评论(7编辑  收藏  举报

导航