วิธีทำ
ใช้ getter (get property) เพื่อตรวจจับการเข้าถึงค่า
ตัวอย่างโค้ด
class Student{
constructor(studentMarks1, studentMarks2){
this.studentMarks1 = studentMarks1;
this.studentMarks2 = studentMarks2;
var alteredValue = this;
this.getValues = {
get studentMarks1() {
return alteredValue.studentMarks1;
},
get studentMarks2() {
return alteredValue.studentMarks2;
}
};
}
}
var johnSmith = new Student(78,79);
console.log("Before incrementing the result is=");
console.log("StudentMarks1="+johnSmith.studentMarks1,"StudentMarks2="+johnSmith.studentMarks2);
johnSmith.studentMarks2+=10;
console.log("After incrementing the value 10 in the studentMarks2, the result is as follows=");
console.log("StudentMarks1="+johnSmith.studentMarks1, "StudentMarks2="+johnSmith.getValues.studentMarks2);
วิธีรัน
node fileName.js
ชื่อไฟล์ demo200.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo200.js Before incrementing the result is= StudentMarks1=78 StudentMarks2=79 After incrementing the value 10 in the studentMarks2, the result is as follows= StudentMarks1=78 StudentMarks2=89
คำอธิบาย
ใช้ getter ใน object getValues เพื่อเข้าถึงค่าล่าสุดของ properties
เมื่อ johnSmith.studentMarks2 += 10 เปลี่ยนค่าโดยตรงjohnSmith.getValues.studentMarks2 ใช้ getter อ่านค่าใหม่ (89) ได้ถูกต้อง