javascript写的代理函数

来源:互联网 发布:怎么重装windows xp 编辑:程序博客网 时间:2024/05/17 08:39
(function(){
    var _ = function(name, args){
        if (name) {
            this.name = name
        }
        if (args) {
            this.args = args
        }
    }
    _.prototype.lambda = function(handler, scope){
        if (handler) {
            return this.affix(function(){
                var args = new Array();
                var i = 0;
                for (var j = 0; j < arguments.callee.lamdas.length; j++) {
                    var v = arguments.callee.lamdas[j];
                    if (v.hasOwnProperty("_") && (typeof v == "function")) {
                        var fnt = v();
                        args.push(fnt.g(arguments[i++]));
                    }
                    else if (v == window["_"]) {
                        args.push(arguments[i++]);
                    }
                    else if ((typeof(v) == "object") && (v instanceof window["_"])) {
                        args.push(_(v).apply(arguments[i++]));
                    }
                    else {
                        args.push(v);
                    }
                }
                args.concat((Array.prototype.slice.call(arguments)).slice(i));
                if (arguments.callee.handler instanceof Function) {
                    return arguments.callee.handler.apply(arguments.callee.scope, args);
                }
                else {
                    return arguments.callee.scope[arguments.callee.handler].apply(arguments.callee.scope, args);
                }
            }, {
                handler: handler,
                scope: scope,
                lamdas: (Array.prototype.slice.call(arguments)).slice(2)
            });
        }
        
        return undefined;
    }
    _.prototype.affix = function(fn, args){
        for (var j in args) {
            fn[j] = args[j];
        }
        return fn;
    }
    _.prototype.get = function(name){
        var fnt = function(){
            return new _(name, (Array.prototype.slice.call(arguments)).slice());
        };
        fnt["_"] = true;
        return fnt;
    }
    _.prototype.g = function(target){
        return target ? target[this.name] : undefined;
    }
    window._ = new _();

})()


样例:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>New Web Project</title>
        <script type="text/javascript" src="_.js">
        </script>
        <script type="text/javascript" src="jquery-1.8.0.js">
        </script>
        <script>
            function a(c, b,f){
               alert(c + "=======" + b+"---"+f);
            }
            _.lambda(a, this, _.get("kk"),_.get("name"), "hello")({kk:"lh"},{name:"wl"});
        </script>
    </head>
    <body>
        <h1>New Web Project Page</h1>
    </body>
</html>