ES5、ES6继承

405 阅读1分钟

ES5

先创造子类的【实例对象】this,然后再将父类的方法添加到this上面(Parent.apply(this))

function Father (name) {
  this.name = name
}
Father.action = function () {
  console.log('我在看电视')
}
Father.prototype.say = function () {
  console.log(`我是${this.name}`)
}
let father = new Father('父亲')
console.log(father.name) // 父亲
father.say() // 我是父亲
Father.action() // 我在看电视

function Child (name) {
  Father.call(this, name)
}
Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child
let child = new Child('儿子')
console.log(child.name) // 儿子
child.say() // 我是儿子

ES6

先将父类【实例对象】的属性和方法加到this上面(所以必须先调用super方法),然后再用子类的【构造函数】修改this

class Father {
  constructor (name) {
    this.name = name
  }
  static action () { // 【父类的静态方法,会被子类继承】
    console.log('我在看电视')
  }
  say () {
    console.log(`我是${this.name}`)
  }
}
let father = new Father('父亲')
console.log(father.name) // 父亲
father.say() // 我是父亲
Father.action() // 我在看电视

class Child extends Father { // 【Child.prototype = Object.create(Father.prototype)】
  constructor (name) {
    super(name) // 【Father.call(this, name)】
  }
}
let child = new Child('儿子')
console.log(child.name) // 儿子
child.say() // 我是儿子
Child.action() // 我在看电视
class Father {
  constructor (obj) {
    this._obj = obj
    this.first()
    this.init()
  }
  first () {
    this._name = this._obj.name
  }
  init () {
    console.log('必须实现init')
  }
}

class Child extends Father { // 【Child.prototype = Object.create(Father.prototype)】
  init () {
    console.log(this._name)
  }
}

new Father({ name: '父亲' })
new Child({ name: '儿子' })
// 必须实现init
// 儿子