Getter
เมื่อเข้าถึง property ค่าจะได้จากการเรียกฟังก์ชันโดยนัย (implicitly) ใช้คีย์เวิร์ด get ใน JavaScript อนุญาตให้ใช้ identifier เป็นตัวเลขหรือสตริง
Setter
เมื่อตั้งค่า property จะเรียกฟังก์ชันโดยนัย และค่าถูกส่งเป็น argument คืนค่าเป็น property เอง ใช้คีย์เวิร์ด set ใน JavaScript อนุญาตให้ใช้ identifier เป็นตัวเลขหรือสตริง
ตัวอย่าง
<html>
<body>
<script>
var department = {
deptName: "Finance",
deptZone: "South",
deptID: 105,
get details() {
return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
},
set details(info) {
var res = info.toString().split(' ');
this.deptName = res[0] || '';
this.deptZone = res[1] || '';
this.deptID = res[2] || '';
}
};
department.details = 'Marketing North 001';
document.write(department.deptName);
document.write(department.deptZone);
document.write(department.deptID);
</script>
</body>
</html>
คุณสมบัติของ Getter/Setter
| คุณสมบัติ | Getter | Setter |
|---|---|---|
| Keyword | get | set |
| Parameters | ไม่มี | มี 1 parameter (ค่าที่ assign) |
| Return | คืนค่า (property value) | ไม่คืนค่า (ค่าที่ assign เป็น property value) |
| Invocation | อ่าน property: obj.prop | เขียน property: obj.prop = val |
| ใน Class | get prop() {} | set prop(val) {} |
ตัวอย่างใน Class (ES6+)
class Temperature {
constructor(celsius) {
this._celsius = celsius;
}
get fahrenheit() {
return this._celsius * 9/5 + 32;
}
set fahrenheit(value) {
this._celsius = (value - 32) * 5/9;
}
}
const temp = new Temperature(25);
console.log(temp.fahrenheit); // 77 (getter)
temp.fahrenheit = 100; // setter
console.log(temp._celsius); // 37.78
Object.defineProperty (Legacy)
const obj = {};
Object.defineProperty(obj, 'prop', {
get() { return this._value; },
set(val) { this._value = val; },
enumerable: true,
configurable: true
});