C# 開發者習慣了屬性變更通知(delegate、event)與 FileSystemWatcher 這類機制,寫 JavaScript 時不免會想:變數的值被改掉時,能不能攔下來做點事?
最直覺的做法是模仿 C# 的屬性寫法——不直接改私有變數,而是透過 setXxx 方法,並在其中觸發變更回呼。
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();
缺點很明顯:開發者必須自律地永遠走 setter,一旦有人直接改內部變數就攔不住。
Mozilla 曾提供 Object.watch()/Object.watch() 這對方法專門用來監聽屬性變更,寫起來非常優雅,可惜在 IE 等瀏覽器上完全不能用,標準化途中也被移除。
社群流傳一個做法,透過 Object.defineProperty(ES5)或 __defineGetter__/__defineSetter__(舊瀏覽器)攔截讀寫:
if (!Object.prototype.watch) {
Object.prototype.watch = function (prop, handler) {
var oldval = this[prop],
newval = oldval,
getter = function () { return newval; },
setter = function (val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
};
if (delete this[prop]) {
if (Object.defineProperty) { // ECMAScript 5
Object.defineProperty(this, prop, { get: getter, set: setter });
} else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
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;
};
}
這段程式碼在當年是很好的思路,但以現在的標準來看,更推薦以下方式:
defineProperty 做不到的操作,是 Vue 3 與現代狀態管理的基礎。
const state = new Proxy({ count: 0 }, {
set(target, prop, value) {
const old = target[prop];
target[prop] = value;
console.log(`${String(prop)} 從 ${old} 變成 ${value}`);
return true;
}
});
state.count = 5; // count 從 0 變成 5
另外提醒:直接擴充 Object.prototype 會汙染所有物件並干擾 for...in 枚舉,實務上應避免。