class是一種物件導向的程式(Object-oriented programming),物件導向是一種將程式資料封裝及相關操作模組化的程式設計方式,物件導向有自己的狀態及行為。
支援物件導向語言利用繼承(JS extends)達到代碼重用和可擴展特性
class mobilePhone {
constructor(brand, type) {
this.brand = brand
this.type = type
}
getInfo () {
return `廠牌${this.brand}型號${this.type}`
}
}
class mobilePhone {
constructor(type) {
this.type = type
}
}
class iPhone extends mobilePhone {
// type 為繼承參數, brand為iPhone class自有屬性
constructor (type, brand) {
// class 繼承需透過super傳遞
// super會參照父類別的建構子
// super繼承type後不用宣告this.type屬性,就會有mobilePhone中的type值
super (type)
this.brand = brand
}
getInfo () {
console.log(this)
}
}
多型 (Polymorphism)
相同名稱的方法(Method),傳入不參數會執行不同敘述,多型(Polymorphism)包含 多載(Overloading) 和 複寫(Overriding)
覆寫 ⇒ 覆蓋掉父元素的方法
可以看到右邊原先父層的getInfo方法被覆蓋掉了
參考:
https://totoroliu.medium.com/物件導向-object-oriented-programming-概念-5f205d437fd6