js 构造函数继承

2016-02-01  本文已影响0人  飞鱼Q

//js对象的继承

    function Animal(){
        this.species = "animal";
    }
    function Cat(name,color){
        this.name = name;
        this.color = color;
    }
    
    
    //1.构造函数绑定——使用call或apply方法,将父对象的构造函数绑定在子对象上
    function Cat(name,color){
        Animal.apply(this,arguments);
        this.name = name;
        this.color = color;
    }
    var cat1 = new Cat("xiao","red");
    console.log("species:"+cat1.species+" name:"+cat1.name+" color:"+cat1.color);
    
    
    
    //2.prototype模式——"猫"的prototype对象,指向一个Animal的实例,那么所有"猫"的实例,就能继承Animal了
    Cat.prototype = new Animal();//将prototype变成animal的实例
    var cat1 = new Cat("xiao","red");
    /*
    任何一个prototype对象都有一个constructor属性,指向它的构造函数(Cat)
     Cat.prototype原来指向的是Cat,因为上面将它替换成了Animal的实例了
     所以它的属性(constructor)也变成了Animal
     */
    console.log(Cat.prototype.constructor == Animal);//true
    /*
    每个实例也有一个constructor属性,默认调用prototype对象的constructor属性。
     */
    console.log(cat1.constructor == Cat.prototype.constructor);//true
    console.log(cat1.constructor == Animal);//true
    //cat1明明是用构造函数Cat生成的,但是现在变成了Animal,所以需要再把它变回原来的Cat
    Cat.prototype.constructor = Cat;
    cat1 = new Cat("xiao","red");
    
    console.log(cat1.species); // animal
    //结论,替换一个构造函数的prototype,一定要将prototype的constructor换回它本身。
    
    //3.利用空对象直接继承prototype
    function extend(parent,child){
        function f(){};
        f.prototype = parent.prototype;
        child.prototype = new f();
        child.prototype.constructor = child;
        child.uber = parent.prototype;//纯粹为了备用,可以调父类的原型 uber意思是上一层
    }
    
    extend(Animal,Cat);
    var cat2 = new Cat("dada","white");
    console.log("species:"+cat2.species+" name:"+cat2.name+" color:"+cat2.color);
    
    //4.拷贝继承——将父类的prototype的属性和方法复制给子类的prototype.
    function extend2(parent,child){
        var p = parent.prototype;
        var c = parent.prototype;
        for(var i in p){
            c[i] = p[i];
        }
        c.uber = p;
    }
    extend2(Animal,Cat);
    var cat3 = new Cat("zhong","black");
    console.log("species:"+cat3.species+" name:"+cat3.name+" color:"+cat3.color);

参考来源:阮一峰博客

上一篇 下一篇

猜你喜欢

热点阅读