组合继承与寄生组合式继承

组合继承

<script type="text/javascript">
    function First(name){
        this.name=name;
        this.colors=["blue","green","red"];
    }
    First.prototype.getName=function(){
        return this.name;
    };

    function Second(name,age){
        First.call(this,name);  //借用构造函数,继承实例属性
        this.age=age;
    }

    Second.prototype=new First();   //原型链实现对原型属性和方法的继承
    Second.prototype.constructor=Second;
    Second.prototype.getAge=function(){
        return this.age;
    };

    var instance1=new Second("chenshaoxiu",22);
    var instance2=new Second("chen",21);

    instance1.colors.push("purple");
    alert(instance1.colors+","+instance1.getName()+","+instance1.getAge()); //blue,green,red,purple,chenshaoxiu,22
    alert(instance2.colors+","+instance2.getName()+","+instance2.getAge()); //blue,green,red,chen,21

  寄生组合式继承

<script type="text/javascript">
    //寄生组合式继承
    //返回构造函数F的一个实例,这个实例的[[Prototype]]属性指向o
    function object(o){
        function F(){}
        F.prototype=o;
        return new F();
    }

    function inheritPrototype(subType,superType){
        var prototype=object(superType.prototype);
        prototype.constructor=subType;      //添加construtor属性
        subType.prototype=prototype;        //让子类型的原型对象指向prototype
    }

    function First(name){
        this.colors=["red","green","blue"];
        this.name=name;
    }
    First.prototype.getName=function(){
        return this.name;
    };

    function Second(name,age){
      First.call(this,name);    //借用构造函数
      this.age=age;
    }
    inheritPrototype(Second,First);
    Second.prototype.getAge=function () {
        return this.age;
    };

    var instance1=new Second("chenshaoxiu",22);
    var instance2=new Second("shaoxiu",21);
    instance1.colors.push("purple");

    alert(instance1.colors+","+instance1.getName()+","+instance1.getAge());//red,green,blue,purple,chenshaoxiu,22
    alert(instance2.colors+","+instance2.getName()+","+instance2.getAge());//red,green,blue,shaoxiu,21

</script>

  

 

posted @ 2018-04-20 19:53  清风☆薰衣草  阅读(231)  评论(0)    收藏  举报