ES五、ES6繼承

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() // 我在看電視
複製代碼
相關文章
相關標籤/搜索