คอนเซปท์ของ Class นั้นเป็นเหมือนกับตัวต้นแบบในการสร้าง Object ขึ้นมา เราสามารถนำ Class ไปใช้ประโยชน์ได้หลายทาง เช่นการแบ่งแยกประเภทข้อมูล หรือกำหนดลักษณะและความสามารถของ Object ที่จะสร้างขึ้นมาได้ ตัวอย่างยอดนิยมของ Class เช่น Car ที่สร้าง Object ต่างๆ ที่มีลักษณะไม่เหมือนกัน เช่นยี่ห้อรถ สี ความเร็ว นำ้หนัก เป็นต้น
JavaScript นั้นมีการใช้คีย์เวิร์ด Class มาตั้งแต่ ES2015 (หรือ ES6) และ TypeScript ก็เพิ่มความสามารถต่างๆ ให้กับตัว Class เพื่อรองรับการใช้ Type และ Interface ด้วย
การสร้าง Class
Syntax การสร้าง Class จะคล้ายกับการประกาศ Interface ดังนี้
class Car {
year: number
color: "green" | "red" | "blue"
}
const c = new Car() // สร้างด้วยคีย์เวิร์ด new
c.year = 2560 // อ่านหรือเขียน year ได้ ตาม type ที่กำหนด
c.color = "red"
ถ้าต้องการให้ Field มีค่าเริ่มต้น ให้ Assign ค่าได้เลยด้านหลัง Field นั้น
class Car {
year: number = 2540 // ให้ค่าเริ่มต้นของ year เป็น 2540
color: "green" | "red" | "blue"
}
const c = new Car()
console.log(c.year) // 2540
หรือถ้าอยากกำหนดค่าเองตั้งแต่ตอน Initialize (new) ให้สร้าง constructor ด้านใน Class
class Car {
year: number
color: "green" | "red" | "blue"
constructor(year = 2540, color = "green") { // ตั้งค่าเริ่มต้นของ year และ color
this.year = year // ใช้ this เพื่อเซ็ตค่าใน Object
this.color = color
}
}
const c = new Car()
console.log(c.year) // 2540
console.log(c.color) // green
const d = new Car(2549, "blue")
console.log(d.year) // 2549
console.log(d.color) // blue
จะเห็นได้ว่าทั้งสอง Class นั้นมี Field color และ Method changeColor เหมือนกัน เราสามารถดึงโค้ดส่วนที่ซำ้ออกมาเป็น Class ใหม่ได้ แล้วใช้ extends เพื่อนำทั้ง Field และ Method มาใช้ (เป็นการ Refactor แบบหนึ่ง)