【JavaScript】js中继承的n种方式-CSDN博客

23 阅读2分钟

文章目录

继承的N种方式

子类能够使用父类的属性和方法

原型链继承

  1. 创建人的类

    function Person(name, age) {
      this.name = name
      this.age = age
    }
    
    Person.prototype.say = function() {
      console.log('说话了')
    }
    
    const p1 = new Person('张三', 19)
    
  2. 创建狗的类

    function Dog(name, age) {
      this.name = name
      this.age = age
    }
    
    Dog.prototype.say = function() {
      console.log('说话了')
    }
    
    const d1 = new Dog('大黄', 3)
    
  3. 狗继承自人的类

    // 创建人的类
    function Person(name, age) {
      this.name = name
      this.age = age
    }
    
    Person.prototype.say = function() {
      console.log('说话了')
    }
    function Dog() {}
    
    // 此方式不推荐 子原型和父原型公用同一个原型
    // Dog.prototype = Person.prototype
    Dog.prototype = new Person()
    
    const d1 = new Dog('大黄', 3)
    

以上则实现原型链继承但是会有以下问题:

  • 包含引用类型值的原型属性会被所有的实例共享

    function Person(name, age) {
      this.name = name
      this.age = age
      this.hobby = []
    }
    
  • 创建子类的时候不能传递参数

借用构造函数继承

  1. 创建人的类

    // 创建人的类
    function Person(name, age) {
      this.name = name
      this.age = age
      this.hobby = []
    }
    
  2. 通过 call 实现

    function Dog(name, age) {
      Person.call(this, name, age)
    }
    
    const d1 = new Dog('大黄', 2)
    const d2 = new Dog('小黄', 1)
    

组合式继承

// 创建人的类
function Person(name, age) {
  this.name = name
  this.age = age
}

Person.prototype.say = function() {
  console.log('说话了')
}
function Dog(name, age) {
  Person.call(this, name, age)
}

// 此方式不推荐 子原型和父原型公用同一个原型
// Dog.prototype = Person.prototype
Dog.prototype = new Person()

const d1 = new Dog('大黄', 3)
const d2 = new Dog('小黄', 2)

寄生式组合继承

Object.create 作用:

  1. 创建对象
  2. 将对象的proto 指向参数对象
// 创建人的类
function Person(name, age) {
  this.name = name
  this.age = age
}

Person.prototype.say = function() {
  console.log('说话了')
}
function Dog(name, age) {
  Person.call(this, name, age)
}

// 此方式不推荐 子原型和父原型公用同一个原型
// Dog.prototype = Person.prototype
Dog.prototype = Object.create(Person.prototype)

const d1 = new Dog('大黄', 3)
const d2 = new Dog('小黄', 2)

es6 类继承

class Person {
  say() {
    console.log('说话了')
  }
}

class Child extends Person {}

const child = new Child()
child.say()