Object.defineProperty之observe实现

时间:2021-08-05 16:13:07

对数据对象的属性批量劫持设置:

<script type="text/javascript">
function observe(data){
if(!data || typeof data !== 'object'){
return;
} Object.keys(data).forEach(function(key){
// value 而不是直接用data[key]: defineProperty时,data[key]会导致死循环
var value = data[key];
observe(value);
Object.defineProperty(data,key,{
enumerable: true,
configurable: true,
get: function() {
return value;
},
set: function(newVal) {
value = newVal;
console.log('prop(' + key + ') has been obsered, value: ' + newVal.toString() );
}
});
});
} var json = {
addr1: {
city: ''
},
addr2: ''
};
observe(json);
json.addr1.city = '北京市海淀区'; // prop(city) has been obsered, value: 北京市海淀区
json.addr2 = '上海市外滩'; // prop(addr2) has been obsered, value: 上海市外滩
</script>

后续... ...