JavaScript 原生不支持直接監聽變量變化,但通過封裝 setter、Object.watch (非標準)、ES6 Proxy 等技術可實現響應式數據綁定。本文演示從手動封裝到現代標準方案的演進。
將變量封裝在閉包中,通過方法修改並觸發回調:
function Class1() {
var oldValue = '';
var name = 'xu';
var id = '1';
this.setName = function(n) {
oldValue = name;
name = n;
this.propertyChange('name', oldValue, n);
};
this.setID = function(n) {
oldValue = id;
id = n;
this.propertyChange('id', oldValue, n);
};
this.display = function() {
alert(name + "'s id is: " + id);
};
}
Class1.prototype.propertyChange = function(propertyName, oldValue, newValue) {
alert(propertyName + "'s value changed from " + oldValue + " to " + newValue);
};
var c = new Class1();
c.setName('xu22'); // 觸發監聽
c.setID('5');
c.display();
缺點: 必須通過方法修改,直接賦值 (c.name = 'xxx') 無法攔截。
var obj = { name: 'xu', id: '1' };
obj.watch('name', function(prop, oldVal, newVal) {
console.log(prop + ' changed from ' + oldVal + ' to ' + newVal);
return newVal; // 必須返回新值
});
obj.name = 'xu22'; // 自動觸發 watch 回調
obj.unwatch('name'); // 移除監聽
局限: 非 ECMAScript 標準,Chrome/IE/Edge 不支持,生產環境不可用。
if (!Object.prototype.watch) {
Object.prototype.watch = function(prop, handler) {
var oldVal = this[prop];
var newVal = oldVal;
var getter = function() { return newVal; };
var setter = function(val) {
oldVal = newVal;
return newVal = handler.call(this, prop, oldVal, val);
};
if (delete this[prop]) { // 轉為訪問器屬性
if (Object.defineProperty) { // ES5+
Object.defineProperty(this, prop, { get: getter, set: setter, configurable: true });
} else if (Object.prototype.__defineGetter__) { // 老式瀏覽器
Object.prototype.__defineGetter__.call(this, prop, getter);
Object.prototype.__defineSetter__.call(this, prop, setter);
}
}
};
}
if (!Object.prototype.unwatch) {
Object.prototype.unwatch = function(prop) {
var val = this[prop];
delete this[prop];
this[prop] = val; // 恢復數據屬性
};
}
Proxy 提供強大的元編程能力,可攔截對象所有操作:
function createObservable(target, onChange) {
return new Proxy(target, {
set(obj, prop, value, receiver) {
const oldVal = obj[prop];
const result = Reflect.set(obj, prop, value, receiver);
if (oldVal !== value) {
onChange(prop, oldVal, value);
}
return result;
},
deleteProperty(obj, prop) {
const oldVal = obj[prop];
const result = Reflect.deleteProperty(obj, prop);
if (oldVal !== undefined) {
onChange(prop, oldVal, undefined);
}
return result;
}
});
}
// 使用
const state = createObservable({ count: 0, name: 'init' }, (prop, oldVal, newVal) => {
console.log(`[監聽] ${prop}: ${oldVal} → ${newVal}`);
});
state.count = 1; // [監聽] count: 0 → 1
state.name = 'new'; // [監聽] name: init → new
delete state.name; // [監聽] name: new → undefined
| 特性 | Vue 2 (Object.defineProperty) | Vue 3 (Proxy) |
|---|---|---|
| 監聽新增屬性 | 需 $set / Vue.set | 原生支持 |
| 監聽數組索引/長度 | 需特殊處理 | 原生支持 |
| 性能 | 遞歸遍歷對象屬性 | 按需代理,惰性響應 |
| 瀏覽器支持 | IE9+ | 現代瀏覽器 (需 Polyfill 兼容 IE) |