ด้วยสํานึกในพระมหากรุณาธิคุณสมเด็จพระนางเจ้าสิริกิติ์เป็นล้นพ้นอันหาที่สุดมิได้


การใช้งาน Getter, Setter และ Private Variable ในภาษา TypeScript

บทความ เมื่อไม่กี่สัปดาห์ โดย Ninenik Narkdee
typescript

คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ typescript

ดูแล้ว 78 ครั้ง


ในแนวคิดการเขียนโปรแกรมเชิงวัตถุ (OOP) การควบคุมการเข้าถึงข้อมูลของวัตถุ (Encapsulation) เป็นสิ่งสำคัญ TypeScript ใช้ Access Modifiers ในการซ่อนข้อมูล (Private Variables) และใช้ Custom Accessors (get และ set) เพื่อควบคุมการอ่านและเขียนค่าอย่างปลอดภัย

 

1. การกำหนด Private Variable (Encapsulation)

 

ใน TypeScript เราใช้คีย์เวิร์ด private เพื่อกำหนดให้คุณสมบัติ (Property) หรือเมธอด (Method) เข้าถึงได้เฉพาะภายใน Class นั้น ๆ เท่านั้น ซึ่งแตกต่างจาก Dart ที่ใช้เครื่องหมาย _ (Underscore) นำหน้าเพื่อกำหนดความเป็นส่วนตัวในระดับ Library

การใช้ private เป็นมาตรฐาน OOP สากล และเป็นวิธีที่แนะนำในการซ่อนข้อมูลที่สำคัญ เช่น ยอดเงิน หรือรหัสผ่าน

TypeScript
class Product {
    // 1. Private Variable: ใช้ _ นำหน้าชื่อเพื่อเป็นธรรมเนียม แต่ 'private' คือคีย์เวิร์ดที่ทำให้มันเป็น Private จริงๆ
    private _price: number; 

    constructor(initialPrice: number) {
        this._price = initialPrice;
    }

    // Method สาธารณะที่เข้าถึงตัวแปรส่วนตัวได้
    public getDetail(): string {
        return `Product price is ${this._price} THB.`;
    }
}

const item = new Product(500);

// item._price; // Error (ใน TypeScript): Property '_price' is private.
item.getDetail(); // ทำงานได้

 

2. การใช้งาน Getter (Accessors)

 

Getter หรือ Accessor คือฟังก์ชันที่ใช้คีย์เวิร์ด get เพื่ออนุญาตให้อ่านค่าคุณสมบัติที่เป็น private หรือคำนวณค่าใด ๆ ก่อนส่งกลับออกไป โดยภายนอกจะเข้าถึงเหมือนเป็นตัวแปร (Property) ปกติ

ประโยชน์: ใช้ในการ คำนวณ ข้อมูล หรือใช้ในการ แปลง ข้อมูลก่อนส่งออก

TypeScript
class Robot {
    private _height: number; // ความสูงเป็นหน่วย cm
    private _calcWeight: number; // น้ำหนักที่ถูกคำนวณ

    constructor(height: number) {
        this._height = height;
        this._calcWeight = 0; // ค่าเริ่มต้น
    }

    // Custom Getter: เข้าถึงผ่าน robot.weight
    public get weight(): number {
        // สามารถเพิ่มตรรกะหรือการตรวจสอบก่อนคืนค่าได้
        return this._calcWeight;
    }
    
    // Default Getter: สำหรับความสูง เข้าถึงผ่าน robot.height (ถ้าไม่มี set/get กำหนดไว้)
    public get height(): number {
        return this._height;
    }
    
    // ... Custom Setter จะอยู่ด้านล่าง
}

const humanoidA = new Robot(200);
// console.log(humanoidA._height); // Error เพราะเป็น private
console.log(`Height (via getter): ${humanoidA.height}`); // Output: 200
console.log(`Weight (via getter): ${humanoidA.weight}`); // Output: 0

 

3. การใช้งาน Setter (Accessors)

 

Setter คือฟังก์ชันที่ใช้คีย์เวิร์ด set เพื่อควบคุมการกำหนดค่าให้กับคุณสมบัติที่เป็น private หรือเพื่อเพิ่มการตรวจสอบความถูกต้องของข้อมูลก่อนการกำหนดค่า

ประโยชน์: ใช้ในการ ตรวจสอบ (Validation) ความถูกต้องของข้อมูล หรือใช้ในการ คำนวณ ค่าอื่น ๆ จากข้อมูลที่ส่งเข้ามา

TypeScript
// ต่อจาก Class Robot เดิม:

class Robot {
    private _height: number;
    private _calcWeight: number;

    constructor(height: number) {
        this._height = height;
        this._calcWeight = 0;
    }
    
    // Custom Getter (เหมือนเดิม)
    public get weight(): number {
        return this._calcWeight;
    }

    // Custom Setter: เข้าถึงผ่าน robot.weight = value
    // รับค่า percent เพื่อคำนวณน้ำหนักจากเปอร์เซ็นต์ของความสูง
    public set weight(percent: number) {
        // การตรวจสอบความถูกต้อง (Validation)
        if (percent < 0 || percent > 100) {
            console.error("Error: Weight percentage must be between 0 and 100.");
            return;
        }
        // การคำนวณก่อนกำหนดค่า
        this._calcWeight = (this._height * percent) / 100;
        console.log(`Weight set to ${percent}% of height.`);
    }
}

const humanoidB = new Robot(200);

humanoidB.weight = 50; // เรียกใช้ Setter
console.log(`Calculated Weight: ${humanoidB.weight}`); // Output: 100

humanoidB.weight = 120; // เรียกใช้ Setter (จะแสดง Error ใน Console)
console.log(`Calculated Weight: ${humanoidB.weight}`); // Output: 100 (ค่าเดิม)

 

4. คุณสมบัติ readonly (ค่าคงที่)

 

ใน TypeScript มีคีย์เวิร์ด readonly ซึ่งเป็นอีกรูปแบบของการควบคุมการเข้าถึง โดยใช้กำหนดให้คุณสมบัตินั้นสามารถ อ่านได้เท่านั้น และสามารถกำหนดค่าได้เพียงครั้งเดียวภายใน constructor หรือตอนประกาศ

TypeScript
class User {
    // กำหนดให้ id สามารถอ่านได้ แต่ไม่สามารถแก้ไขได้หลังจากการสร้าง
    public readonly id: number; 
    public name: string;

    constructor(id: number, name: string) {
        this.id = id; // สามารถกำหนดค่าได้ใน constructor
        this.name = name;
    }
}

const userA = new User(101, "Alice");
// userA.id = 102; // Error: Cannot assign to 'id' because it is a read-only property.
userA.name = "Bob"; // ทำได้


กด Like หรือ Share เป็นกำลังใจ ให้มีบทความใหม่ๆ เรื่อยๆ น่ะครับ



อ่านต่อที่บทความ



ทบทวนบทความที่แล้ว









เนื้อหาที่เกี่ยวข้อง



Tags:: typescript







URL สำหรับอ้างอิง










เว็บไซต์ของเราให้บริการเนื้อหาบทความสำหรับนักพัฒนา โดยพึ่งพารายได้เล็กน้อยจากการแสดงโฆษณา โปรดสนับสนุนเว็บไซต์ของเราด้วยการปิดการใช้งานตัวปิดกั้นโฆษณา (Disable Ads Blocker) ขอบคุณครับ