javascript实现yield的方法

时间:2013-11-06    点击:92   

没想到代码一次测试成功.~~只不过是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.

判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解
addEventListener()第三个参数useCapture (Boolean)详细解析
zTree插件之单选下拉菜单实例代码
jQuery把表单元素变为json对象
JQuery插件开发示例代码
> 返回     
地址:上海市普陀区胶州路941号长久商务中心 电话: QQ:
© Copyright 2012 上海网络 Product All Rights Reserved