Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Khác biệt Getter và Setter trong JavaScript


Getter

Khi truy cập property, giá trị được lấy qua việc gọi function ngầm. Dùng từ khóa get.

Setter

Khi gán property, function được gọi ngầm với giá trị làm argument. Giá trị trả về được set cho property. Dùng từ khóa set.

Ví dụ triển khai cả hai

<html>
  <body>
    <script>
      var department = {
        deptName: "Finance",
        deptZone: "South",
        deptID: 105,
        // Getter
        get details() {
          return "Department Details<br>" + 
                 "Name: " + this.deptName + " <br>" +
                 "Zone: " + this.deptZone + "<br>" +
                 "ID: " + this.deptID;
        },
        // Setter
        set details(info) {
          var res = info.toString().split(' ');
          this.deptName = res[0] || '';
          this.deptZone = res[1] || '';
          this.deptID = res[2] || '';
        }
      };
      
      // Gọi setter (gán như property)
      department.details = 'Marketing North 001';
      
      // Gọi getter (đọc như property)
      document.write(department.deptName); // "Marketing"
      document.write(department.deptZone); // "North"
      document.write(department.deptID);   // "001"
    </script>
  </body>
</html>

Đặc điểm chính

Đặc điểmGetterSetter
Từ khóagetset
Kích hoạtKhi đọc property (obj.prop)Khi ghi property (obj.prop = val)
Tham sốKhông cóMột tham số (giá trị gán)
ReturnGiá trị propertyGiá trị trả về bị bỏ qua (property = argument)
Có thể chỉ có getter?Có (read-only property)Phải có getter đi kèm (trừ hiếm)

Ví dụ thực tế: Validation, Computed Property

class User {
  constructor(name) {
    this._name = name; // Convention: _prefix cho backing store
  }
  
  get name() {
    return this._name.toUpperCase(); // Computed on read
  }
  
  set name(value) {
    if (!value || value.trim().length < 2) {
      throw new Error("Name phải có ít nhất 2 ký tự");
    }
    this._name = value.trim();
  }
  
  // Read-only property (chỉ getter)
  get createdAt() {
    return new Date(); // Mỗi lần đọc khác nhau
  }
}

const user = new User("alice");
console.log(user.name); // "ALICE"
user.name = "  bob  ";  // Setter validate & trim
console.log(user.name); // "BOB"
// user.createdAt = new Date(); // ❌ Error: no setter

Object.defineProperty (ES5 way)

const obj = {};
let internal = 0;

Object.defineProperty(obj, 'count', {
  get() { return internal; },
  set(v) { 
    if (typeof v === 'number' && v >= 0) internal = v; 
  },
  enumerable: true,
  configurable: true
});