ES6-Class類2/2

1.ES5中的繼承

(JS繼承的幾種方式,挖個坑,待填)

function Food() {
  this.type = 'food'
}
Food.prototype.getType = function() {
  return this.type
}
function Vegetables(name) {
  this.name = name
}
// Vegetables繼承Food
Vegetables.prototype = new Food()
const tomato = new Vegetables('tomato')
console.log(tomato.getType())

2.ES6中Class繼承

class Parent {
  constructor(name) {
    this.name = name
  }
  getName() {
    return this.name
  }
  static getNames() {
    return `Inner ${this.name}`
  }
}
class Child extends Parent {
  constructor(name, age) {
    super(name) // 子類必須調用super函數 之後才能使用this
    this.age = age
  }
}
const c = new Child('dan', 3)
console.log(c)
console.log(c.getName())
console.log(c instanceof Child) // true
console.log(c instanceof Parent) // true
console.log(Child.getNames()) // Inner Child
console.log(Parent.getNames()) // Inner Parent
// console.log(c.getNames()) // undefined 該static方法不被繼承

3.Object.getPrototypeOf() 獲取原型對象

console.log(Object.getPrototypeOf(Child) === Parent) // true

4. super

  • super作爲函數,代表父類的構造函數constructor。

          子類繼承時constructor裏需要調用super()函數,super()中的傳參和父類constructor中的傳參一樣。

  •  super作爲對象

          普通方法中,指向的是父類的原型對象

          static靜態方法中,指向的是父類

class Parent2 {
  constructor() {
    this.type = 'Parent'
  }
  getName() {
    return this.type
  }
}
Parent2.getType = () => {
  return 'is Parent'
}

class Child2 extends Parent2 {
  constructor() {
    super()
    console.log('constructor ' + super.getName())
  }
  getParentName() {
    console.log('getParentName ' + super.getName())
  }
  getParentType() {
    console.log('getParentType ' + super.getType())
  }
  static getParentType2() {
    console.log('getParentType ' + super.getType())
  }
}

const cc = new Child2() // constructor Parent
cc.getParentName() // getParentName Parent
// cc.getParentType() // super指向的是父類的原型對象,getType()定義在父類上,無法訪問
Child2.getParentType2() // getParentType is Parent  static靜態方法,super指向父類,可以訪問getType()

// 在父類的原型上定義方法,方法裏的this指向子類的實例
class Parent3 {
  constructor() {
    this.name = 'parent'
  }
  print() {
    console.log(this.name)
  }
}

class Child3 extends Parent3 {
  constructor() {
    super()
    this.name = 'child'
  }
  childPrint() {
    super.print()
  }
}
// super只能 1.作爲函數使用 2.作爲對象,調用上面的方法或屬性
const d = new Child3()
d.childPrint()

5.類中的prototype屬性和__proto__屬性

var obj = new Object()
console.log(obj.__proto__ === Object.prototype) // true

// 子類的__proto__指向的是父類本身
// 子類的prototype屬性的__proto__指向的是父類的prototype屬性
// 實例的__proto__屬性的__proto__指向的是父類實例的__proto__

6. ES6 原生構造函數的繼承

原生構造函數  Boolean Number String Array Date Function RegExp Error Object

ES5中無法繼承  ES6可繼承

// ES6 原生構造函數的繼承

class CustomArray extends Array {
  constructor(...args) {
    super(...args)
  }
}
const arr = new CustomArray(3, 3, 1, 9, 7)
console.log(arr) // 長度爲3的空數組
// console.log(arr.fill('+')) // ['+', '+', '+']
console.log(arr.join('_')) // +_+_+

open day + salary day
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章