萬盛學電腦網

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

JavaScript 監聽變量變化:從手動封裝到 Object.watch 及 Proxy 現代方案

前言

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') 無法攔截。

二、Object.watch / unwatch (非標準,僅 Firefox 支持)

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 不支持,生產環境不可用。

三、Polyfill 實現:基於 __defineSetter__ (舊版瀏覽器)


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; // 恢復數據屬性
    };
}

四、現代標準方案:ES6 Proxy (推薦)

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/3 響應式原理對比

特性Vue 2 (Object.defineProperty)Vue 3 (Proxy)
監聽新增屬性需 $set / Vue.set原生支持
監聽數組索引/長度需特殊處理原生支持
性能遞歸遍歷對象屬性按需代理,惰性響應
瀏覽器支持IE9+現代瀏覽器 (需 Polyfill 兼容 IE)

六、總結與選型建議

  • 簡單場景/學習:手動封裝 setter 方法最直觀可控
  • 舊項目維護/需兼容 IE:Object.defineProperty 方案 (如 Vue 2)
  • 現代項目/新架構:Proxy 是首選,功能完整、性能優、符合標準
  • 避免使用:Object.watch/unwatch (非標準、僅 Firefox)
  • 進階需求:集成成熟響應式庫 (Vue Reactivity、MobX、RxJS) 而非重複造輪子
copyright © 萬盛學電腦網 all rights reserved