JS 如何实现继承?

93 阅读1分钟

方法一:使用原型链

    function Animal(legsNumber){
      this.legsNumber = legsNumber
    }
    Animal.prototype.kind = '动物'

    function Dog(name){
      Animal.call(this, 4)  // this.legsNumber = 4
      this.name = name
      // this.legsNumber = 4;
    }
    // Dog.prototype.__proto__ = Animal.prototype  // 但这句代码被禁用了,怎么办
    // Dog.prototype = new Animal()  // 缺点:这样我的Dog的原型上会得到legsNumber
    /* 
        new 经历了什么?
          1. 创建临时对象
          2. this = 临时对象
          3. this.__proto__ = 构造函数的prototype
          4. 执行构造函数
          5. return this
    */
    var F = function(){}
    F.prototype = Animal.prototype
    Dog.prototype = new F()
    // 能共享的放在原型上面,不一定是方法才放在原型上面
    Dog.prototype.say = function(){
      console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
    }
    Dog.prototype.kind = '狗'

    const d1 = new Dog("啸天")
    d1.say()
    const d2 = new Dog("啸天2")
    d2.say()
    console.log(d2);

方法二:使用 class

class Animal{
  constructor(legsNumber){
    this.legsNumber = legsNumber
  }
  run(){}
}
class Dog extends Animal{
  constructor(name) {
    super(4)
    this.name = name
  }
  say(){
    console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
  }
}