Accessor property (thuộc tính truy cập) giúp triển khai getter và setter trong JavaScript. Chúng thực thi một hàm khi đọc (get) hoặc ghi (set) giá trị.
Có 4 đặc tính của accessor property:
- get – Được gọi khi đọc thuộc tính. Không nhận đối số.
- set – Được gọi khi gán giá trị cho thuộc tính. Nhận đúng 1 đối số (giá trị mới).
- enumerable – Cho phép thuộc tính xuất hiện khi duyệt (ví dụ
for...in,Object.keys()) khi làtrue. - configurable – Khi
false, không thể xóa thuộc tính hay thay đổi các đặc tính của nó.
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Accessor property</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 và các đặc tính</h1> <div class="result"></div> <br /> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để dùng get/set sửa đổi và hiển thị thuộc tính person</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>Sau khi sửa occupation <br>"; person.occupation = "Developer"; resEle.innerHTML += "New Occupation = " + person.occupation; }); </script> </body> </html>
Kết quả
Khi nhấn nút:
- Name = Rohan : Occupation = Student
- Sau khi sửa occupation
- New Occupation = Developer
Getter fullname cho phép đọc như thuộc tính bình thường (person.fullname). Setter job cho phép gán person.job = "Developer" nhưng thực tế gán vào occupation. Đây là cách đóng gói logic validation, tính toán dẫn xuất, v.v.