Accessor Property ช่วยให้เราสร้าง Getter และ Setter ฟังก์ชันใน JavaScript ได้ พวกมันจะทำงานเมื่อมีการอ่านหรือตั้งค่าคุณสมบัติ
มีแอตทริบิวต์ 4 ตัวสำหรับ Accessor Property ดังนี้
- get − เรียกเมื่ออ่านคุณสมบัติ ไม่รับอาร์กิวเมนต์
- set − เรียกเมื่อตั้งค่าคุณสมบัติ รับอาร์กิวเมนต์เพียง 1 ตัว
- enumerable − อนุญาตให้วนลูปออบเจ็กต์ได้เมื่อเป็น true
- configurable − เมื่อเป็น false จะไม่สามารถลบคุณสมบัติหรือเปลี่ยนค่าได้
โค้ดตัวอย่างสำหรับ Accessor Property และแอตทริบิวต์ ด้านล่าง
ตัวอย่าง
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Accessor property and its attributes</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to use set and get to modify and display person object properties</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let person = { name: "Rohan", age: 22, occupation: "Student", get fullname() { return this.name; }, set job(occupation) { this.occupation = occupation; }, }; BtnEle.addEventListener("click", () => { resEle.innerHTML = "Name = " + person.fullname + " : Occupation = " + person.occupation; resEle.innerHTML += "<br>After modifying occupation property <br>"; person.occupation = "Developer"; resEle.innerHTML += "New Occupation = " + person.occupation; }); </script> </body> </html>ผลลัพธ์

เมื่อคลิกปุ่ม ‘CLICK HERE’ −
