Dùng getter trong JavaScript để truy cập property như property (không cần dấu ngoặc). Từ khóa 'get' làm việc này.
Ví dụ 1: Gọi như function (sai ngữ cảnh)
<html> <body> <p id = "prop"></p> <script> var business = { product: "Tutorix", parent : "Tutorialspoint", get details() { return this.product+" is the product of" + " " + this.parent; } }; document.getElementById("prop").innerHTML = business.details(); </script> </body> </html>
Ví dụ 2: Gọi như property (đúng)
Bỏ dấu ngoặc, 'get' xử lý property "details" như property.
<html> <body> <p id = "prop"></p> <script> var business = { product: "Tutorix", parent : "Tutorialspoint", get details() { return this.product+" is the product of" + " " + this.parent; } }; document.getElementById("prop").innerHTML = business.details; </script> </body> </html>
Kết quả
Tutorix is the product of Tutorialspoint
Giải thích: get details() định nghĩa accessor property. Truy cập obj.details (không có dấu ngoặc) tự động gọi getter. Dùng cho computed property, validation, lazy loading.