Classes & Advanced OOP
class อยู่ทั้งสองโลก
หัวข้อที่มีชื่อว่า “class อยู่ทั้งสองโลก”เกือบทุกอย่างในคอร์สนี้เป็น type — construct ที่อยู่ตอน compile time แล้วถูก erase ทิ้ง แต่ class ต่างออกไป เป็นหนึ่งในไม่กี่ declaration ที่สร้างทั้ง type และ value ชื่อ class เป็น type ที่คุณเอาไป annotate ได้ และในเวลาเดียวกันก็เป็น runtime constructor ที่เรียกด้วย new ได้
class User { constructor(public name: string) {}}
const u: User = new User("Ada"); // `User` เป็น TYPE (annotation) และ VALUE (constructor)ธรรมชาติสองด้านนี้คือเหตุผลที่ class รู้สึกพิเศษ และเป็นเหตุผลที่ feature ของตัวเองแบ่งเป็นสองกลุ่ม: กลุ่มที่ compiler เช็คแล้ว erase (เช่น private) กับกลุ่มที่รอดไปถึง JavaScript ที่ emit ออกมา (เช่น #private field)
โมดูลนี้ครอบคลุมอะไรบ้าง
หัวข้อที่มีชื่อว่า “โมดูลนี้ครอบคลุมอะไรบ้าง”| บทเรียน | สิ่งที่คุณจะได้เรียนรู้ |
|---|---|
| Classes, deep | access modifier, readonly, parameter property, static, abstract, implements |
this types & polymorphism | polymorphic this, this parameter และ pitfall เรื่อง binding ใน type system |
| Decorators | decorator แบบ stage-3 สมัยใหม่ — class, method, field และ factory |
| Mixins & composition | สร้าง behavior จาก class factory ที่ compose ได้ แทน hierarchy ลึก ๆ |
พูดถึง inheritance สักหน่อย
หัวข้อที่มีชื่อว่า “พูดถึง inheritance สักหน่อย”TypeScript รองรับ extends inheritance แบบคลาสสิก แต่โมดูลนี้เน้นไปที่ feature ที่ community ใช้จริงใน code สมัยใหม่: composition over inheritance class hierarchy ที่ลึกมัก brittle ส่วน this type, decorator และ mixin ช่วยให้สร้าง behavior ที่ยืดหยุ่นและ reuse ได้โดยไม่ต้องพึ่ง inheritance
flowchart TB cls["class declaration"] --> typeworld["TYPE world (erased): private, protected, implements, abstract"] cls --> valueworld["VALUE world (runtime): #private, static, the constructor, methods"]