class Observer {
constructor(value){
this.value = value
if(Array.isArray(value)){
// 数组的逻辑
}else {
// 对象的逻辑
this.walk(value)
}
}
walk(obj) {
const keys = Object.keys(obj)
for(let i = 0;i <= keys.length;i++){
defineReactive(obj,keys[i])
}
}
}
function defineReactive(obj,key){
let val = obj[key]
if(typeof val === 'object'){
new Observer(val)
}
Object.defineProperty(obj,key,{
get(){
console.log(`${key}属性背读取了`)
return val
},
set(newValue){
console.log(`${key}的属性背修改了,新值为${newValue}`)
val = newValue
}
})
}
const obj = {
a:1,
b:2,
c:{
d:1
}
}
const newObj = new Observer(obj)
标签:Vue,keys,实现,value,walk,侦听器,obj
From: https://www.cnblogs.com/landuo629/p/17092425.html