美文网首页
面向对象继承的方式

面向对象继承的方式

作者: tenro | 来源:发表于2022-08-09 10:23 被阅读0次

    创建父类

    function Animal(name){
      this.name = name
      this.sleep = function(){
        console.log(this.name + '正在睡觉!');
      }
    }
    Animal.prototype.eat = function(food){
      console.log(this.name + '继承吃' + food + '的方法!');
    }
    // 创建实例
    var animal = new Animal("旺财");
    console.log(animal.name);    //  旺财
    animal.eat('骨头');  //  旺财继承吃骨头的方法!
    animal.sleep();    //  旺财正在睡觉!
    

    原型链继承:将父类的实例作为子类的原型

    function Cat(){}
    Cat.prototype = new Animal();
    Cat.prototype.name = "喵喵";
    
    var cat = new Cat();
    console.log(cat.name)    // 喵喵
    cat.eat("鲫鱼");    //  喵喵继承吃鲫鱼的方法!
    cat.sleep();    // 喵喵正在睡觉!
    
    console.log(cat instanceof Animal)    // true
    console.log(cat instanceof Cat);    // true
    
    优点:
        1、非常纯粹的继承关系,实例是子类的实例,也是父类的实例
        2、父类新原型方法和属性,子类都能访问到
    
    缺点:
        1、想为子类增加属性和方法,必须先实例化父类 new Animal()
        2、无法实现多继承
        3、来自原型对象的引用属性被所有实例共享
        4、创建子类实例时,无法向父类构造函数传参
    

    借用构造函数继承:在子类型构造函数的内部调用父类的构造函数

    function Cat(name){
        Animal.call(this);
        this.name = name || "Tom";
    }
    Cat.prototype.eat = function(food){
        console.log(this.name + "自带吃" + food + "的方法!")
    }
    var cat = new Cat("喵喵");
    console.log(cat.name)    // 喵喵
    cat.eat("鲫鱼");    //  喵喵自带吃鲫鱼的方法!
    cat.sleep();    // 喵喵正在睡觉!
    
    console.log(cat instanceof Animal)    // false
    console.log(cat instanceof Cat);    // true
    
    优点:
        1、子类和父类属性不共享
        2、创建子类实例时可以向父类传递参数
        3、可以实现多继承(通过call调用多个父类对象)
    
    缺点:
        1、实例并不是父类的实例,只是子类的实例(不在一个原型链上)
        2、只能继承父类的实例属性和方法,不能继承父类原型属性和方法
        3、无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
    

    组合继承:借用父类构造函数和实例进行组合继承

    function Cat(name) {
        Animal.call(this);
        this.name = name
    }
    Cat.prototype = new Animal();
    Cat.prototype.constructor = Cat;
    
    var cat = new Cat("喵喵");
    console.log(cat.name);    // 喵喵
    cat.eat("鲫鱼");    //    喵喵继承吃鲫鱼的方法!
    cat.sleep();    // 喵喵正在睡觉!
    
    console.log(cat instanceof Animal)    // true
    console.log(cat instanceof Cat);    // true
    
    优点:
        1、弥补了借用构造函数继承方式的缺陷, 可以继承实例属性和方法,也可以继承原型属性和方法
        2、即使子类的实例,也是父类的实例
        3、不存在引用属性共享的问题
        4、函数可以传参也可复用
    
    缺点:
        1、调用了两次父类构造函数,生成了两份实例
    

    寄生继承:

    function Cat(name){
        Animal.call(this);
        this.name = name;
    }
    function F(){}
    F.prototype = Animal.prototype;
    Cat.prototype= new F();
    Cat.prototype.costructor = Cat;
    
    var cat = new Cat("喵喵");
    console.log(cat.name);    // 喵喵
    cat.eat("鲫鱼");    //    喵喵继承吃鲫鱼的方法!
    cat.sleep();    //  Uncaught TypeError: cat.sleep is not a function-报错,只继承了父类Animal上构造函数的属性及方法
    
    有点
    

    相关文章

      网友评论

          本文标题:面向对象继承的方式

          本文链接:https://www.haomeiwen.com/subject/oofyirtx.html