• JS继承2


    一.原型链继承

    关键步骤:

    • 让子类的原型对象成为父类的实例

    • 矫正子类构造器属性

     1 function Animal(name,age){
     2   this.name = name;
     3   this.age = age;
     4 }
     5 
     6 Animal.prototype.eat = function(){
     7   console.log("Animal eat");
     8 }
     9 
    10 function Cat(name,age){
    11   this.name = name;
    12   this.age = age;
    13 }
    14 
    15 //让子类的原型对象成为父类的实例
    16 Cat.prototype = new Animal();
    17 
    18 //当使用原型继承的时候,注意矫正子类的构造器属性
    19 Cat.prototype.constructor = Cat;
    20 
    21 var tom = new Cat('tom',3);
    22 tom.eat();

    二.借用构造函数继承

    借用构造函数继承是伪继承:原型链上找不到父类的实例(son.__proto__..... != father.prototype)

     1     function Animal(name, age) {
     2       this.name = name;
     3       this.age = age;
     4     }
     5     //子类没有继承父类的方法,子类原型链上找不到父类的实例为伪继承
     6     Animal.prototype.eat = function () {
     7       console.log("Animal eat");
     8     }
     9 
    10     function Cat(name, age, sex) {
    11 
    12       //借用构造函数继承方式1
    13       Animal.call(this, name, age);
    14 
    15       //借用构造函数继承方式2
    16       // Animal.apply(this, [name, age]);
    17 
    18 
    19       this.sex = sex;
    20     }
    21 
    22 
    23     var tom = new Cat('tom', 3, 'boy');

    三.组合继承:前两种方式加在一起

     1     function Animal(name, age) {
     2       this.name = name;
     3       this.age = age;
     4     }
     5 
     6     Animal.prototype.eat = function () {
     7       console.log("Animal eat");
     8     }
     9 
    10     function Cat(name, age, sex) {
    11 
    12       //借用构造函数继承方式1
    13       // Animal.call(this, name, age);
    14 
    15       //借用构造函数继承方式2
    16       Animal.apply(this, [name, age]);
    17 
    18 
    19       this.sex = sex;
    20     }
    21 
    22     //让子类的原型对象成为父类的实例
    23     Cat.prototype = new Animal();
    24 
    25     //当使用原型继承的时候,注意矫正子类的构造器属性
    26     Cat.prototype.constructor = Cat;
    27 
    28 
    29     var tom = new Cat('tom', 3, 'boy');
    30 
    31     console.log(tom)

  • 相关阅读:
    测开之路九十五:css进阶之光标和溢出内容处理
    测开之路九十四:css之盒子模型
    测开之路九十三:css之文字样式和段落对齐
    测开之路九十二:css之背景色和背景
    测开之路九十一:css常用的选择器
    测开之路九十:css的引用方式
    测开之路八十九:HTML之图片处理
    测开之路八十八:HTML之文本格式化
    测开之路八十七:HTML之a标签的用法
    十、Django之Admin
  • 原文地址:https://www.cnblogs.com/zhihaospace/p/12005211.html
Copyright © 2020-2023  润新知