JS监听变量变化

单个属性变化监听:Object.defineProperty(obj, prop, descriptor)

//监听a对象的age属性
var a = { age: 10 };
Object.defineProperty(a, 'age', {
    get: function() { //取值的时候会触发
        console.log('get: ', age);  
        return age;
    },
    set: function(value) { //更新值的时候会触发
        age = value;
        console.log('set: ', age); 
    }
});

a.age; //get: 10
a.age = 20; //set: 20

多个属性变化监听: Object.defineProperties(obj,props)

var obj = {};
Object.defineProperties(obj, {
    a: {
        configurable: true,
        get: function() {
            console.log('get: ', a);
            return a;
        },
        set: function(value) {
            a = value;
            console.log('set: ', a);
        }
    },
    b: {
        configurable: true,
        get: function() {
            console.log('get: ',b);
            return b;
        },
        set: function(value) {
            b = value;
            console.log('set: ', b);
        }
    }
});

你可能感兴趣的:(JS监听变量变化)