ใช้คีย์เวิร์ด get เพื่อสร้าง getter function
ตัวอย่าง
const studentDetails = {
studentName: "David Miller",
get studentName() {
console.log('I am calling the getter method...')
}
}
console.log(studentDetails.studentName);
เพื่อรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้:
ผลลัพธ์มีดังนี้:
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo221.js
ผลลัพธ์
ผลลัพธ์มีดังนี้:
PS C:\Users\Amit\JavaScript-code> node demo221.js I am calling the getter method... Undefined