js实现继承的方法

124 阅读1分钟

父类构造函数

function Animal(name) {
  this.name=name;
  this.sleep = function () {
    console.log('is sleep')
  }
}
Animal.prototype.eat =function (food) {
  console.log(this.name+' is eating ' +food)
}

原型继承

无法向父类方法中传递参数

function Cat() {
  
}
Cat.prototype = new Animal()
Cat.prototype.name ='122'

构造函数继承

父类原型上的方法不能用

function Cat() {
  Animal.call(this,...arguments)
}

组合继承

多次调用父类的构造函数

function Cat(name) {
  Animal.call(this,...arguments)
}
Cat.prototype = new Animal()

寄生继承

原型不能复用

function Cat(name) {
  var o  = Object.create(Animal.prototype)
  o.yy = function () {
    console.log('haha')
  }
}

寄生组合继承

function Cat(name) {
  Animal.call(this,...arguments) // 继承父类的实例属性
  var o  = Object.create(Animal.prototype)//创建父类原型的副本
  o.constructor = Cat // 将副本的构造函数指向cat
  Cat.protptype = o // 子类的原型指向父类的副本
}

class extends继承

寄生组合继承和class继承的区别
寄生组合继承创建了一个父类的副本,class直接使用父类