let data = {
a:1,
b:2,
c:[1,3,5]
}
function updateView(){
console.log("视图更新...")
}
const oldArrayProperty = Array.prototype;
const arrProto = Object.create(oldArrayProperty);
['push','pop','shift','unshift','splice'].forEach(methodName=>{
arrProto[methodName] = function (){
updateView();
oldArrayProperty[methodName].call(this,...arguments);
}
})
function defineReactive(target,key,value){
observer(value)
Object.defineProperty(target,key,{
get(){
return value;
},
set(newValue){
if(newValue !== value){
observer(newValue);
value = newValue;
updateView();
}
}
})
}
function observer(target){
if(typeof target !== 'object' || target === null) return target;
if(Array.isArray(target)){
target.__proto__ = arrProto;
}
for(let key in target){
defineReactive(target,key,target[key])
}
}
observer(data);
data.a = 3;
data.b = 5;
data.c.push(5)
data.c.push(5)
data.c.push(5)
console