ใช้ Getter ใน JavaScript สามารถเข้าถึง Property เป็น Property แบบอื่นได้ ใช้คีย์เวิร์ด 'get' มาดูรายละเอียดกัน
ตัวอย่าง
ในตัวอย่างนี้ Property 'details' ถูกใช้เป็น Function คือ 'details()' จึงไม่ได้ผลลัพธ์ แต่หากเอาวงเล็บออก คีย์เวิร์ด 'get' จะทำให้ Property "details" ถูกจัดว่าเป็น Property ไม่ใช่ Function
<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>
ตัวอย่าง
ที่นี่ เนื่องจาก วงเล็บ ถูกลบออก คีย์เวิร์ด 'get' ทำให้ Property "details" เป็น Property ไม่ใช่ Function
<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>
ผลลัพธ์
Tutorix is the product of Tutorialspoint