class是一種物件導向的程式(Object-oriented programming),物件導向是一種將程式資料封裝及相關操作模組化的程式設計方式,物件導向有自己的狀態及行為。

Class & Object

支援物件導向語言利用繼承(JS extends)達到代碼重用和可擴展特性

class mobilePhone {
	constructor(brand, type) {
		this.brand = brand
		this.type = type
	}
	getInfo () {
		return `廠牌${this.brand}型號${this.type}`
	}
}

截圖 2021-10-04 下午12.10.27.png

截圖 2021-10-04 下午12.15.10.png

三大特性(封裝、繼承、多型)

截圖 2021-10-04 下午12.10.27.png

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)
  }
}

截圖 2021-10-04 下午2.42.53.png

截圖 2021-10-04 下午3.12.23.png

截圖 2021-10-04 下午3.16.39.png

參考:

https://totoroliu.medium.com/物件導向-object-oriented-programming-概念-5f205d437fd6

https://zh.wikipedia.org/wiki/面向对象程序设计

https://ithelp.ithome.com.tw/articles/10109161 ⇒ js封裝