# 继承的实现

本文参考30 分钟学会 JS 继承 (opens new window)较多,勿怪。

# 常用继承

# 复制继承

就是将被继承的类的prototype复制。

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
function Child(name) {
    this.name = name;
}

Object.assign(Child.prototype, Parent.prototype);

var child = new Child('son');
child.sayName();    // child name: son

console.log(child instanceof Parent); //false

缺点

  1. 效率低
  2. instanceof无效
  3. 父亲构造函数没有执行,所以只是继承了方法,而没有继承属性

# 原型继承

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
function Child(name) {
    this.name = name;
}

Child.prototype = new Parent('father');
Child.prototype.constructor = Child;

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

var child = new Child('son');
child.sayName();    // child name: son

console.log(child instanceof Parent); //true

缺点

  1. 子类无法给父类传递参数,在面向对象的继承中,我们总希望通过 child = new Child('son', 'father') 让子类去调用父类的构造器来完成继承。而不是通过像这样new Parent('father') 去调用父类。
  2. Child.prototype.sayName 必须写在 Child.prototype = new Parent('father') 之后,不然会被覆盖掉。

# 构造继承

主要是利用callapply,在子类的环境里,运行一遍父类的属性与方法。

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
Parent.prototype.doSomthing = function() {
    console.log('parent do something!');
}
function Child(name, parentName) {
    Parent.call(this, parentName);
    this.name = name;
}

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

var child = new Child('son');
console.log(child instanceof Parent);//false

child.sayName();      // child name: son
child.doSomthing();   // TypeError: child.doSomthing is not a function

相当于 Parent 这个函数在 Child 函数中执行了一遍,并且将所有与 this 绑定的变量都切换到了 Child 上,这样就克服了前一种方式带来的问题。

缺点

  1. 没有原型,每次创建一个 Child 实例对象时候都需要执行一遍 Parent 函数,无法复用一些公用函数。

    也就是说,只复用了父类属性,而没有复用方法。

  2. instanceof无效

# 组合继承

function Parent(name) {
    this.name = name;
}

Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}
Parent.prototype.doSomething = function() {
    console.log('parent do something!');
}
function Child(name, parentName) {
    Parent.call(this, parentName); //第2次调用
    this.name = name;
}

Child.prototype = new Parent(); //第1次调用
Child.prototype.constructor = Child;
Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

var child = new Child('son');
child.sayName();       // child name: son
child.doSomething();   // parent do something!
console.log(child instanceof Parent);//true

组合式继承是比较常用的一种继承方法,其背后的思路是使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。

这样,既通过在原型上定义方法实现了函数复用,又保证每个实例都有它自己的属性。

缺点

使用过程中会被调用两次:一次是创建子类型的时候,另一次是在子类型构造函数的内部。

# 寄生组合继承

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}

function Child(name, parentName) {
    Parent.call(this, parentName);
    this.name = name;
}

function create(proto) {
    function F(){}
    F.prototype = proto;
    return new F();
}

Child.prototype = create(Parent.prototype);
Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}
Child.prototype.constructor = Child;

var parent = new Parent('father');
parent.sayName();    // parent name: father


var child = new Child('son', 'father');
child.sayName();     // child name: son
console.log(child instanceof Parent);//true

这就是所谓的寄生组合式继承方式,跟组合式继承的区别在于,他不需要在一次实例中调用两次父类的构造函数,假如说父类的构造器代码很多,还需要调用两次的话对系统肯定会有影响,寄生组合式继承的思想在于:用一个 F 空的构造函数去取代执行了 Parent 这个构造函数。

在上面的代码中,我们手动创建了一个 create 函数,但是其实是存在于 Object 对象中,不需要我们手动去创建,所以上面的代码可以改为:

function Parent(name) {
    this.name = name;
}
Parent.prototype.sayName = function() {
    console.log('parent name:', this.name);
}

function Child(name, parentName) {
    Parent.call(this, parentName);
    this.name = name;
}

function inheritPrototype(Parent, Child) {
    Child.prototype = Object.create(Parent.prototype);   //修改
    Child.prototype.constructor = Child;
}

inheritPrototype(Parent, Child);

Child.prototype.sayName = function() {
    console.log('child name:', this.name);
}

var parent = new Parent('father');
parent.sayName();      // parent name: father

var child = new Child('son', 'father');
child.sayName();       // child name: son
console.log(child instanceof Parent);//true

# es6继承

es6本身有class,可以当作prototype的语法糖。

class Parent {
    constructor(name) {
	    this.name = name;
    }
    doSomething() {
	    console.log('parent do something!');
    }
    sayName() {
	    console.log('parent name:', this.name);
    }
}

class Child extends Parent {
    constructor(name, parentName) {
      super(parentName);
      this.name = name;
    }
    sayName() {
 	    console.log('child name:', this.name);
    }
}

const child = new Child('son', 'father');
child.sayName();            // child name: son
child.doSomething();        // parent do something!

const parent = new Parent('father');
parent.sayName();           // parent name: father
console.log(child instanceof Parent);//true

# 多重继承

# es5的多重继承

我们常用的多重继承,一般是继承一个父类,也就是说继承它的属性和方法,再继承其它父类的方法。 实现方法也很简单,在前面继承的基础上,再复制下其它父类的prototype

/**
 * 继承
 * @param {Function} subClass 子构造函数
 * @param {Function} superClass 父构造函数
 */
function extend (subClass, superClass) {
  // const F = function () {
  // };
  // F.prototype = superClass.prototype;
  // subClass.prototype = new F();
  subClass.prototype = Object.create(superClass.prototype);
  subClass.prototype.constructor = subClass;
  subClass.superclass = superClass.prototype;
  if (superClass.prototype.constructor === Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  }
  if (!subClass.prototype.__extendList) {
    subClass.prototype.__extendList = [];
  } else {
    subClass.prototype.__extendList = clone(subClass.prototype.__extendList);
  }
  subClass.prototype.__extendList.push(superClass);
}

/*
 * 多重继承
 * 对于子类和父类重复的成员,会取子类的成员
 * 对于父类重复的成员,会取最后一个父类的成员
 * 如果使用 instanceof 会和第一个父类的成员匹配
 * @param {Function} subClass 子构造函数
 * @param {Function} superClass 父构造函数
 * @param {Boolean} replaceExistedMember 是否替换已有的原型函数。如果为是,则将会是superClasses最后一个的原型函数内容
 */
function multiExtend (subClass, superClasses, replaceExistedMember = true) {
  extend(subClass, superClasses[0]);
  for (let i = 1; i < superClasses.length; i++) {
    let curSuperClass = superClasses[i];
    for (let cur in curSuperClass.prototype) {
      if (cur === 'constructor') {
        continue;
      }
      if (replaceExistedMember) {
        subClass.prototype[cur] = curSuperClass.prototype[cur];
      } else {
        if (subClass.prototype[cur] === undefined || subClass.prototype[cur] === null) {
          subClass.prototype[cur] = curSuperClass.prototype[cur];
        }
      }
    }
    subClass.prototype.__extendList.push(curSuperClass);
  }
}

/**
 * 判断继承
 * @param {Object} subObj 子对象实例
 * @param {Function} superClass 父构造函数
 */
function isInstance (subObj, superClass) {
  if (subObj instanceof superClass) {
    return true;
  }
  if (subObj && subObj.__extendList) {
    if (subObj.__extendList.includes(superClass)) {
      return true;
    }
  }
  return false;
}

function Parent(name) {
  this.parentName = name;
}

Parent.prototype.sayName = function() {
  console.log('parent name:', this.parentName);
};

function Parent2(age) {
  this.age = age; //这句不会走
}
Parent2.prototype.sayAge = function() {
  console.log('parent2 age:', this.age); //undefined
};

function Child(name, parentName) {
  Child.superclass.constructor.call(this, parentName);//必须有这一句,才能继承父类的属性
  this.name = name;
}
//extend(Child, Parent);//单重继承
multiExtend(Child, [Parent, Parent2]);//混合继承

let child = new Child('child', '父亲名称');
console.log(child instanceof Parent); //true
console.log(child instanceof Parent2); //false

console.log(isInstance(child, Parent));//true
console.log(isInstance(child, Parent2));//true

child.sayName();
child.sayAge();

# es6的多重继承

ES6中,class原生是不支持多重继承的,根据阮一峰ECMAScript 6 入门教程 (opens new window)中的方法,通过以下方式即可实现class继承多个类:

function mix(...mixins) {
  class Mix {
    constructor() {
      for (let mixin of mixins) {
        copyProperties(this, new mixin()); // 拷贝实例属性
      }
    }
  }

  for (let mixin of mixins) {
    copyProperties(Mix, mixin); // 拷贝静态属性
    copyProperties(Mix.prototype, mixin.prototype); // 拷贝原型属性
  }

  return Mix;
}

function copyProperties(target, source) {
  for (let key of Reflect.ownKeys(source)) {
    if ( key !== 'constructor'
      && key !== 'prototype'
      && key !== 'name'
    ) {
      let desc = Object.getOwnPropertyDescriptor(source, key);
      Object.defineProperty(target, key, desc);
    }
  }
}

缺点

  1. 构造函数没有传递参数,所以仅适用于不需要有参数的类
  2. 无法使用instanceof

所以像es5一样,仅执行第一个父类的构造函数比较合理。修改为以下内容:

function mix (...mixins) {
  class Mix {
    // 如果不需要拷贝实例属性下面这段代码可以去掉
    constructor (...args) {
      // for (let mixin of mixins) {
      //     copyProperties(this, new mixin()); // 拷贝实例属性
      // }
      copyProperties(this, new mixins[0](...args));
    }
  }

  for (let mixin of mixins) {
    copyProperties(Mix, mixin);
    copyProperties(Mix.prototype, mixin.prototype);
  }

  return Mix;
}

function copyProperties (target, source) {
  for (let key of Reflect.ownKeys(source)) { //返回一个由目标对象自身的属性键组成的数组
    if (typeof source === 'function') { //如果是类,才这样复制
      if (key !== "constructor" && key !== "prototype" && key !== "name") {
        let desc = Object.getOwnPropertyDescriptor(source, key);//返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)
        Object.defineProperty(target, key, desc);
      }
    } else {
      target[key] = source[key];
    }
  }
}

/**
 * 增加一条多重继承的关系链
 */
const multiExtend = function (subClass, superClasses) {
  if (!subClass.prototype.__extendList) {
    subClass.prototype.__extendList = [];
  }
  subClass.prototype.__extendList.push(...superClasses);
};

/**
 * 继承判断
 * @param obj 实例对象
 * @param superClass 父类
 * @return {boolean}
 */
const isInstance = (obj, superClass) => {
  if (obj instanceof superClass) {
    return true;
  }
  if (obj && obj.__extendList) {
    if (obj.__extendList.includes(superClass)) {
      return true;
    }
  }
  return false;
};

class Parent {
  constructor (name, sex) {
    console.log('-----------parent-------' + name);
    this.name = name;
    this.sex = sex;
  }

  saySex () {
    console.log('parent sex:' + this.sex);
  }

  sayName () {
    console.log('parent name:', this.name);
  }
}

class Parent2 {
  constructor (age) {
    console.log('-----------parent2'); //这行不会走
    this.age = age;
  }

  sayAge () {
    console.log('parent age:', this.age); //undefined
  }
}

class Child extends mix(Parent, Parent2) {
  constructor (name, sex, interest) {
    super(name, sex);
    this.interest = interest;
  }
}
multiExtend(Child, [Parent, Parent2]); //必须加这句,才能使用isInstance

const child = new Child('son', 'man', 'football');

child.sayName();  // child name: son
child.saySex();   // parent sex : man
child.sayAge(); //parent age: undefined

console.log(child instanceof Parent);//false
console.log(child instanceof Parent2);//false

console.log(isInstance(child, Parent));//true
console.log(isInstance(child, Parent2));//true

TIP

如果也需要执行其它父类的构造函数,则需要检查程序设计上是否合理了