js 多态实现


js多态实现,并且newObj()函数的传参,继承以最后的对象的属性和方法进行覆盖
(function(){
    //newObj// 可传入构造函数或者json对象,
    function forObj(o1){
        function for_(object1,object2){
            for(var j in object2){object1[j]=object2[j];}
        }
        var opt=Object.prototype.toString.call(o1);
        var obj0={};
        if(opt=='[object Function]'){
            for_(obj0,new o1());
        }else if(opt=='[object Object]'){
            for_(obj0,o1);
        }
        if(o1.prototype){
            var obj1=o1.prototype;
            for_(obj1,obj0);
            return obj1;
        }else{
            return obj0;
        }
    }

    function newObj(){
        var json={};
        var a=arguments;
        for(var i=0;i<a.length;i++){
            var obj=forObj(a[i]);
            for(var j in obj){
                json[j]=obj[j];
            }
        }
        return json;
    }

    function objects(){
        this.color='black';
    }
    objects.prototype={
      name:'baidu'
    };

    function cat2(){
        this.age=1;
        this.type='cat1';
        this.oninit=function(){
            console.log(this);
        }
    }
    cat2.prototype= {
        age:3,
        type:'cat2',
        initialize:function(){
            this.oninit();
        }
    };

    var cat1={
        age:5,
        type:'cat3'
    };

    function dog1(){
        this.age=3;
        this.type='dog1';
        this.oninit=function(){
            console.log(this);
        }
    }
    dog1.prototype= {
        age:2,
        type:'dog2',
        initialize:function(){
            this.oninit();
        }
    };

    var dog2={
        age:1,
        type:'dog3'
    };

    var cat=newObj(objects,cat1,cat2);
    var dog=newObj(objects,dog2,dog1);

    console.log(JSON.stringify(cat));//{"name":"baidu","color":"black","age":1,"type":"cat1"}
    console.log(JSON.stringify(dog));//{"name":"baidu","color":"black","age":3,"type":"dog1"}

    cat.initialize();
    dog.initialize();

})();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值