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 歲)"
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"
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;
}
}
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;
}
}
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; // 觸發回調
| 特性 | 存取器 | 資料屬性 |
|---|---|---|
| 可攔截讀寫 | ✅ | ❌ |
| 可設定 enumerable | ✅ | ✅ |
| 可設定 configurable | ✅ | ✅ |
| 原型鏈繼承 | ✅ | ✅ |
| JSON.stringify | 只序列化 getter 返回值 | 直接序列化值 |
set name(v) { this.name = v; } 會導致無限遞歸,必須用內部屬性 this._name。get: () => this.x 中 this 指向錯誤,必須用傳統函數或簡寫語法。super.get / super.set(需用 Object.getOwnPropertyDescriptor)。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)均以此為核心實現響應式系統,深入理解存取器有助於掌握框架底層原理。