การเขียนโปรแกรมเชิงวัตถุ (Object-Oriented Programming: OOP) เป็นแนวคิดที่มองทุกสิ่งในโปรแกรมเป็น "วัตถุ" (Object) โดย Object จะถูกสร้างขึ้นจาก "พิมพ์เขียว" ที่เรียกว่า Class TypeScript รองรับหลักการ OOP ได้อย่างสมบูรณ์ ทำให้โค้ดมีโครงสร้างที่ชัดเจนและสามารถนำกลับมาใช้ใหม่ได้ง่าย
1. การกำหนด Class และ Object
Class คือพิมพ์เขียวหรือแม่แบบ (Blueprint) ที่กำหนดคุณสมบัติ (Properties) และพฤติกรรม (Methods) ของ Object
Object คือสิ่งที่ถูกสร้างขึ้นจาก Class นั้น ๆ (Instance)
ตัวอย่างการกำหนด Class
class Rectangle {
// 1. Properties (คุณสมบัติ/ตัวแปรสมาชิก) พร้อมกำหนดชนิดข้อมูล
width: number;
height: number;
// 2. Constructor (ตัวสร้าง) - ใช้ในการกำหนดค่าเริ่มต้นเมื่อสร้าง Object
constructor(w: number, h: number) {
this.width = w; // กำหนดค่า w ที่รับเข้ามาให้กับ property width ของ Object
this.height = h;
}
// 3. Methods (เมธอด/ฟังก์ชัน) - พฤติกรรมของ Object
area(): number {
return this.width * this.height;
}
}
// การสร้าง Object (Instance)
const myRectangle = new Rectangle(50, 20);
// การเรียกใช้ Properties และ Methods
console.log(`Width: ${myRectangle.width}`); // Output: 50
console.log(`Area: ${myRectangle.area()}`); // Output: 1000
2. Access Modifiers (การควบคุมการเข้าถึง)
TypeScript มีคุณสมบัติในการควบคุมการเข้าถึง (Encapsulation) ของ Properties และ Methods อย่างชัดเจน โดยใช้คีย์เวิร์ด 3 ตัว ซึ่งเป็นคุณสมบัติที่สำคัญและไม่มีใน JavaScript มาตรฐาน (แตกต่างจาก Dart ที่ใช้ _ นำหน้าเพื่อหมายถึง private)
| Modifier | คำอธิบาย |
| public | สามารถเข้าถึงได้จากทุกที่ (ค่าเริ่มต้นหากไม่ระบุ) |
| private | สามารถเข้าถึงได้เฉพาะภายใน Class นั้น ๆ เท่านั้น |
| protected | สามารถเข้าถึงได้ภายใน Class นั้น และ Class ลูกที่สืบทอดไปเท่านั้น |
ตัวอย่าง:
class BankAccount {
public owner: string; // เข้าถึงได้จากภายนอก
private _balance: number; // เข้าถึงได้เฉพาะใน Class เท่านั้น
constructor(owner: string, initialBalance: number) {
this.owner = owner;
this._balance = initialBalance;
}
// Public method
public deposit(amount: number): void {
this._balance += amount;
}
// Public method ที่เข้าถึง private property
public getBalance(): number {
return this._balance;
}
}
3. Shorthand Initialization (การประกาศคุณสมบัติแบบย่อ)
TypeScript มีวิธีที่กระชับในการประกาศ Properties และกำหนดค่าเริ่มต้นพร้อมกันใน Constructor โดยการใส่ Access Modifier (เช่น public, private) ไว้หน้าพารามิเตอร์ของ Constructor
class Circle {
// TypeScript จะประกาศ public radius: number; ให้โดยอัตโนมัติ
constructor(public radius: number) {
// ไม่จำเป็นต้องใช้ this.radius = radius; อีกต่อไป
}
public circumference(): number {
return 2 * Math.PI * this.radius;
}
}
const myCircle = new Circle(7);
console.log(myCircle.circumference());
4. การสืบทอด (Inheritance)
Inheritance คือการสร้าง Class ใหม่ (Class ลูก หรือ Subclass) ที่รับเอาคุณสมบัติและพฤติกรรมทั้งหมดของ Class เดิม (Class แม่ หรือ Superclass) มาใช้ โดยใช้คีย์เวิร์ด extends
A. การใช้งาน extends และ super()
เมื่อ Class ลูกมี Constructor ของตัวเอง จะต้องเรียกใช้ super() เป็นคำสั่งแรกภายใน Constructor เพื่อเรียกตัวสร้างของ Class แม่ก่อน
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0): void {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
// Override Constructor ของ Class แม่
constructor(name: string) {
super(name); // เรียก constructor ของ Animal (name)
}
// Override Method ของ Class แม่
move(distance: number = 5): void {
super.move(distance); // เรียก method move() ของ Class แม่
console.log("...and wagged its tail!");
}
// New Method
bark(): void {
console.log("Woof! Woof!");
}
}
const puppy = new Dog("Buddy");
puppy.move(10);
// Output: Buddy moved 10m.
// Output: ...and wagged its tail!
B. Static Members
Static Members เป็น Properties หรือ Methods ที่เป็นของ Class นั้น ๆ เอง ไม่ใช่ของ Object ที่ถูกสร้างขึ้นมา (Instance) โดยใช้คีย์เวิร์ด static
class Configuration {
// Static Property: เข้าถึงผ่านชื่อ Class
static version: string = '1.0.0';
// Static Method
static getVersionInfo(): string {
return `App Version: ${Configuration.version}`;
}
}
// เรียกใช้โดยตรงจากชื่อ Class
console.log(Configuration.getVersionInfo()); // Output: App Version: 1.0.0
// ไม่สามารถเรียกผ่าน Object ได้
// const config = new Configuration();
// config.version; // Error
5. การใช้ Getters และ Setters
Getters และ Setters คือ Methods ที่ใช้เพื่อควบคุมการเข้าถึงหรือการเปลี่ยนแปลงค่าของ Properties ภายใน Class (มักใช้กับ private properties) ซึ่งช่วยให้สามารถใส่เงื่อนไขหรือตรรกะก่อนการอ่านหรือเขียนค่าได้
class Product {
private _price: number;
constructor(initialPrice: number) {
this._price = initialPrice;
}
// Getter: ใช้ 'get' เพื่อเข้าถึงค่าแบบ property (product.price)
public get price(): number {
return this._price;
}
// Setter: ใช้ 'set' เพื่อกำหนดค่าแบบ property (product.price = 150)
public set price(newPrice: number) {
if (newPrice < 0) {
console.error("Price cannot be negative.");
return;
}
this._price = newPrice;
}
}
const item = new Product(100);
item.price = 150; // เรียกใช้ Setter
console.log(item.price); // เรียกใช้ Getter (Output: 150)
item.price = -50; // เรียกใช้ Setter (จะแสดง Error ใน Console)