单个属性变化监听:Object.defineProperty(obj, prop, descriptor)
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;
a.age = 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);
}
}
});