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

Định nghĩa Getter và Setter Functions trong JavaScript


Getter

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

Setter

Khi gán property, function gọi ngầm với giá trị làm argument. Dùng từ khóa set.

Ví dụ triển khai

<html>
  <body>
    <script>
      var department = {
        deptName: "Marketing",
        deptZone: "North",
        deptID: 101,
        get details() {
          return "Department Details<br>" + 
                 "Name: " + this.deptName + " <br>" +
                 "Zone: " + this.deptZone + "<br>" +
                 "ID: " + this.deptID;
        },
        set details(info) {
          var words = info.toString().split(' ');
          this.deptName = words[0] || '';
          this.deptZone = words[1] || '';
          this.deptID = words[2] || '';
        }
      };
      
      department.details = 'Marketing North 001'; // Gọi setter
      document.write(department.deptName); // "Marketing"
      document.write(department.deptZone); // "North"
      document.write(department.deptID);   // "001"
    </script>
  </body>
</html>

Cú pháp tổng quát

const obj = {
  // Data property (backing store)
  _value: 0,
  
  // Accessor property - getter
  get value() {
    return this._value;
  },
  
  // Accessor property - setter
  set value(v) {
    this._value = v;
  }
};

// Usage
obj.value = 42;  // setter
console.log(obj.value); // 42 - getter

Object.defineProperty (ES5 - flexible hơn)

const obj = {};
let internal = 0;

Object.defineProperty(obj, 'value', {
  get() { return internal; },
  set(v) { 
    if (typeof v === 'number') internal = v;
  },
  enumerable: true,    // Liệt kê trong for...in, Object.keys
  configurable: true   // Có thể delete, redefine
});

Smart Getter/Setter Patterns

// 1. Lazy initialization (tính toán lần đầu, cache)
class Expensive {
  get data() {
    if (!this._cache) {
      this._cache = computeExpensive(); // Chạy 1 lần
    }
    return this._cache;
  }
}

// 2. Validation & Coercion
class Temperature {
  set celsius(val) {
    this._kelvin = Number(val) + 273.15; // Coerce & validate
  }
  get celsius() { return this._kelvin - 273.15; }
  get fahrenheit() { return this.celsius * 9/5 + 32; } // Computed
}

// 3. Read-only (chỉ getter)
const constants = {
  get PI() { return Math.PI; }
  // Không có setter → read-only
};

Tóm tắt

  • get: Đọc property → chạy function, return value.
  • set: Gán property → chạy function với argument.
  • Dùng cho: validation, computed property, lazy init, read-only, proxy/logging.
  • Object.defineProperty: kiểm soát chi tiết (enumerable, configurable).