js模拟java的spring

<script type="text/javascript">



//模拟 map
var Map = function(){
    this.m = {};
}
Map.prototype = {
    put : function(k,v){
        this.m[k] = v;
    },
    get : function(k){
        return this.m[k];
    }
}

//模拟beanFactory
var Spring = {
    objs : new Map(),
    init : function(config){
        for(var i = 0 , j = config.length ; i < j ; i++){
            var cfg = config[i];
            var ret = this.create(cfg);
            this.objs.put(ret[0],ret[1]);
        }
    },
    get : function(k){
        return this.objs.get(k);
    },
    create : function(cfg){
        var f = new Function();
        f.prototype = window[cfg.fn].prototype;
        var _instance = new f();
       
        var args = [];
        if(cfg.pro){
            for(var pro in cfg.pro){
                if(cfg.pro[pro].v){
                    args.push(cfg.pro[pro].v)
                }
                if(cfg.pro[pro].c){
                    args.push(this.get(cfg.pro[pro].c))
                }
            }
        }
        window[cfg.fn].apply(_instance,args);
        return [cfg.id,_instance]
    }
}


//模拟applicationContext.xml
var cfg = [
    //模拟bean
    {
        id : "c2", // bean的id
        fn : "C2"  // bean的class
    },
    {
        id : "c1",
        fn : "C1",
        pro : {//构造函数的参数
            arg1 : {v:"vvv"}, //v :代表直接赋值 (spring 配置文件中的 value="...")
            arg2 : {v:"bbb"},
            arg3 : {c:"c2"} //c : 配置中其他bean的id(spring 配置文件中的 ref bean = "...")
        }
    }
]


//客户端

var C1 = function(x,y,z){
    this.a = x;
    this.b = y;
    this.c = z;
    this.s = this.c.add(this.a,this.b);
    var _this = this;
    this.z = function(){alert(_this.a + "|||||" +  _this.b)}
}

var C2 = function(){
    this.add = function(a,b){return a + b};淘宝女装夏装新款
    this.toString = function(){return "C2"}
}


Spring.init(cfg); //加载配置
var  c1 = Spring.get("c1"); //从beanfactory中获取bean

alert(c1.s);
c1.z();坏帐

</script>
posted @ 2011-05-18 09:26  ctou45  阅读(230)  评论(0编辑  收藏  举报