几种继承方式

86 阅读1分钟

原型继承

Son.prototype = new Father()

缺陷:

  • 不能给父构造函数传参
  • 共享的引用属性容易被篡改

构造继承

Father.call(this)

缺陷:

  • 只是执行了父类函数,并没有继承父类的 prototype 所以如果想定义公共方法就得这样写
function Father () {
  this.attr = 'demo'
  this.fn = () => {}
}
  • 明明可以共用的fn,在每个实例中都保存了一份,浪费了内存;
  • 实例只是 instance 子类, 而不能 instance 父;

组合继承

Father.call(this)
Son.prototype = new Father()

function Father() {
    this.name = 'f'
    this.age = 55
}

缺陷:

  • new Father() 和 Father.call(this) 都有生成一份属性(name, age),内存的浪费

完美的寄生组合继承

Father.call(this)
Object.create(Father.prototype)