js继承之组合继承

554 阅读2分钟

这是我参与更文挑战的第8天,活动详情查看:更文挑战

构造函数继承

我们在上一篇原型链继承的文章中了解到了原型链继承的优缺点,那既然知道了优点我们就要发扬光大,缺点就要弥补,而要解决这个缺点就用到了我们接下来要了解到的构造函数继承。

  • 实现原理:在子类的构造函数中,通过apply或者call的形式,调用父类构造函数,以实现继承。 话不多说,上才(代)艺(码):
function Parent(parent){
    this.parent = parent
}
Parent.prototype.getName = function(){
    console.log(this.parent)
}
function Child(name,child){
    Parent.call(this, name)
    this.child = child
}

let child1 = new Child('我是child1', '嗯啊')
console.log(child1) // {parent: '我是child1', child: '嗯啊'}
let child2 = new Child('我是child2', '哦哦')
console.log(child2) // {parent: '我是child2', child: '嗯啊'}
console.log(child1.getName) // 报错
console.log(child1 instanceof Parent) // false
console.log(child1 instanceof Child) // true

上述代码中,可以看到解决了原型链继承的两个缺点,但是这种方式也有其不足之处:

  • 实例并不是父类的实例,仅仅只是子类的实例。
  • 子类无法继承父类原型链上的方法。
  • 每次生成子类实例都会执行一次父函数。

组合继承(原型链继承和借用构造函数继承的组合)

组合继承(combination inheritance),有时候也叫做伪经典继承,指的是将原型链和借用构造函数的技术组合到一块,从而发挥二者之长的一种继承模式。 实现思路是使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。 这样既通过在原型上定义方法实现了函数复用,又能够保证每个实例都有它自己的属性。

//父类:人
    function Person () {
      this.head = '脑袋瓜子';
      this.emotion = ['喜', '怒', '哀', '乐']; //人都有喜怒哀乐
    }
    //将 Person 类中需共享的方法放到 prototype 中,实现复用
    Person.prototype.eat = function () {
      console.log('吃吃喝喝');
    }
    Person.prototype.sleep = function () {
      console.log('睡觉');
    }
    Person.prototype.run = function () {
      console.log('快跑');
    }
    //子类:学生,继承了“人”这个类
    function Student(studentID) {
      this.studentID = studentID;
      Person.call(this);
    }
    
    Student.prototype = new Person();  //此时 Student.prototype 中的 constructor 被重写了,会导致 stu1.constructor === Person
    Student.prototype.constructor = Student;  //将 Student 原型对象的 constructor 指针重新指向 Student 本身

    var stu1 = new Student(1001);
    console.log(stu1.emotion); //['喜', '怒', '哀', '乐']

    stu1.emotion.push('愁');
    console.log(stu1.emotion); //["喜", "怒", "哀", "乐", "愁"]
    
    var stu2 = new Student(1002);
    console.log(stu2.emotion); //["喜", "怒", "哀", "乐"]

    stu1.eat(); //吃吃喝喝
    stu2.run(); //快跑
    console.log(stu1.constructor);  //Student

上述代码中,我们将 Person 类中需要复用的方法提取到 Person.prototype 中,然后设置 Student 的原型对象为 Person 类的一个实例,这样 stu1 就能访问到 Person 原型对象上的属性和方法了。其次,为保证 stu1 和 stu2 拥有各自的父类属性副本,我们在 Student 构造函数中,还是使用了 Person.call ( this ) 方法。所以,结合原型链继承和借用构造函数继承,就完美地解决了之前这二者各自表现出来的缺点。