萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Getter/Setter 深度解析:屬性存取器的進階用法與最佳實踐

基本語法

ES5 引入 Object.defineProperty 與對象字面量存取器語法,允許在讀寫屬性時攔截並執行自定義邏輯。

對象字面量寫法(最常用)

const user = {
  _name: '',
  _age: 0,
  
  // 存取器
  get name() {
    console.log('讀取 name');
    return this._name;
  },
  set name(val) {
    console.log('寫入 name:', val);
    if (typeof val !== 'string' || val.length < 2) {
      throw new Error('名稱至少 2 個字符');
    }
    this._name = val.trim();
  },
  
  get age() {
    return this._age;
  },
  set age(val) {
    const num = Number(val);
    if (Number.isNaN(num) || num < 0 || num > 150) {
      throw new Error('年齡必須是 0-150 的數字');
    }
    this._age = num;
  },
  
  // 計算屬性(僅 getter)
  get info() {
    return `${this._name} (${this._age} 歲)`;
  }
};

// 使用:像訪問普通屬性一樣
user.name = 'Lucy';
user.age = 20;
console.log(user.name); // "Lucy"
console.log(user.info); // "Lucy (20 歲)"

Object.defineProperty 寫法(動態添加/更精細控制)

const product = {
  _price: 0,
  _currency: 'CNY'
};

Object.defineProperty(product, 'price', {
  get() { return this._price; },
  set(v) {
    const n = Number(v);
    if (Number.isNaN(n) || n < 0) throw new Error('價格必須 ≥ 0');
    this._price = n;
  },
  enumerable: true,   // 可被 for...in / Object.keys 列舉
  configurable: true  // 可被刪除或重新定義
});

Object.defineProperty(product, 'priceUSD', {
  get() { return (this._price / 7.2).toFixed(2); },
  enumerable: true
  // 無 setter → 唯讀計算屬性
});

product.price = 100;
console.log(product.priceUSD); // "13.89"

進階應用模式

1. 數據驗證與標準化

class User {
  constructor() { this._email = ''; }
  
  get email() { return this._email; }
  set email(v) {
    const cleaned = String(v).trim().toLowerCase();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(cleaned)) {
      throw new Error('郵箱格式無效');
    }
    this._email = cleaned;
  }
}

2. 惰性計算與緩存

class Report {
  constructor(rawData) { this._raw = rawData; }
  
  get summary() {
    if (!this._summaryCache) {
      console.log('計算摘要...');
      this._summaryCache = this._computeSummary();
    }
    return this._summaryCache;
  }
  
  _computeSummary() { /* 昂貴計算 */ }
  
  // 數據變更時清除緩存
  set rawData(v) {
    this._raw = v;
    this._summaryCache = null;
  }
}

3. 代理與觀察者模式(Vue 2 響應式核心思想)

function observe(obj, onChange) {
  const handler = {
    get(target, key, receiver) {
      return Reflect.get(target, key, receiver);
    },
    set(target, key, value, receiver) {
      const oldVal = target[key];
      const result = Reflect.set(target, key, value, receiver);
      if (oldVal !== value) onChange(key, value, oldVal);
      return result;
    }
  };
  return new Proxy(obj, handler);
}

const state = observe({ count: 0 }, (k, n, o) => {
  console.log(`${k}: ${o} → ${n}`);
});
state.count = 1; // 觸發回調

4. 相容性:存取器 vs 資料屬性

特性存取器資料屬性
可攔截讀寫✅❌
可設定 enumerable✅✅
可設定 configurable✅✅
原型鏈繼承✅✅
JSON.stringify只序列化 getter 返回值直接序列化值

常見陷阱

  • 遞歸調用:set name(v) { this.name = v; } 會導致無限遞歸,必須用內部屬性 this._name。
  • 箭頭函數不可用於存取器:get: () => this.x 中 this 指向錯誤,必須用傳統函數或簡寫語法。
  • 繼承時覆蓋:子類重新定義同名存取器會完全覆蓋父類,需手動 super.get / super.set(需用 Object.getOwnPropertyDescriptor)。
  • 效能:存取器比直接屬性訪問略慢(微秒級),熱路徑循環中避免過度使用。

TypeScript 型別宣告

class Config {
  private _apiUrl = '';
  
  get apiUrl(): string { return this._apiUrl; }
  set apiUrl(v: string) {
    if (!/^https?:\/\//.test(v)) throw new Error('必須為 HTTP(S) URL');
    this._apiUrl = v.replace(/\/+$/, ''); // 去除尾部斜槓
  }
  
  // 唯讀計算屬性
  get wsUrl(): string {
    return this._apiUrl.replace(/^http/, 'ws');
  }
}

結語

Getter/Setter 是 JavaScript 物件模型的強大擴展,將「屬性訪問」升級為「可編程的操作」。善用它們可實現驗證、計算屬性、緩存、響應式等模式,但需注意 this 綁定、遞歸陷阱與序列化行為。現代框架(Vue、MobX、Svelte)均以此為核心實現響應式系統,深入理解存取器有助於掌握框架底層原理。

copyright © 萬盛學電腦網 all rights reserved