js实现继承的方式

76 阅读1分钟

1,原型链式继承:将父类的实例作为子类的原型

缺点:创建子类实例时,无法向父类构造函数传参

  //定义一个父类型
  function Animal (name) {
    this.name = name
    this.say = function () {
      console.log(this.name)
    }
  }
  //原型对象方法
  Animal.prototype.eat = function (food) {
    console.log(`${this.name}正在吃${food}`)
  }
  function Cat () { }
  Cat.prototype = new Animal()
  Cat.prototype.name = 'cat'
  const cat = new Cat()
  cat.say() //cat
  cat.eat('猫粮') //cat正在吃猫粮

2,构造函数继承(在子类型中利用Animal.call(this)继承父类型的属性和方法)

  //定义一个父类型
  function Animal (name) {
    this.name = name
    this.say = function () {
      console.log(this.name)
    }
  }
  //原型对象方法
  Animal.prototype.eat = function (food) {
    console.log(`${this.name}正在吃${food}`)
  }
  //子类型中将
  function Cat (name, age) {
    Animal.call(this, name)
    this.age = age
  }
  const cat = new Cat('cat', 16)
  cat.eat('猫粮') //cat正在吃猫粮

3,实例继承(在子类型中创建父类型实例, 然后对父类型实例进行扩展, 最后返回父类型实例)

 // 定义一个父类型
  function Animal (name) {
    this.name = name;
    this.say = function () { console.log(this.name) }
  }
  // 原型对象方法
  Animal.prototype.eat = function (food) {
    console.log(this.name + '吃:' + food);
  };
  function Cat (name, age) {
    var o = new Animal(name); //先创建子类型实例
    o.age = age;
    return o;
  }
  const cat = Cat('cat', 1);
  cat.eat('猫粮')

4,拷贝继承(此方式无法获取父类不可for in遍历的方法)

  // 定义一个父类型
  function Animal (name) {
    this.name = name
    this.say = function () {
      console.log(this.name)
    }
  }
  // 原型对象方法
  Animal.prototype.eat = function (food) {
    console.log(this.name + '吃:' + food)
  }
  function Cat (name, age) {
    const animal = new Animal(name)
    for (var p in animal) {
      Cat.prototype[p] = animal[p]
    }
    this.age = age
  }
  const cat = new Cat('cat', 1)
  cat.eat('猫粮')

5,寄生组合继承

 // 定义一个父类型
  function Animal (name) {
    this.name = name
    this.say = function () {
      console.log(this.name)
    }
  }
  // 原型对象方法
  Animal.prototype.eat = function (food) {
    console.log(this.name + '吃:' + food)
  }
  function Cat (name, age) {
    Animal.call(this, name)
    this.age = age
  }
  (function () { // 创建一个没有实例方法的类
    const Super = function () { }
    Super.prototype = Animal.prototype
    Cat.prototype = new Super() //将实例作为子类的原型
  })()
  const cat = new Cat()

6,class继承

Class 父类型{
    constructor(){
    }
    …
}
Class 子类型 extends 父类型{
    constructor(){
        super()
    }
}