Proxy
let person = {
name:"ss",
hobby:["1" , "2" , "3"],
zhang:{
wang:{name:"sssss"}
}
}
//递归处理多重嵌套Proxy响应式处理
const handler = {
get(target, key, recevier) {
console.log("dule");
return addSubProxy(Reflect.get(target, key, recevier))
},
set(target, key, value , recevier) {
console.log("写了");
return Reflect.set(target, key, value , recevier)
}
}
function addSubProxy(subObj) {
if(typeof subObj !== "object"){
return subObj
}
//
return new Proxy(subObj, handler)
}
let p = addSubProxy(person);
console.log(p);
结果
对于p.zhang.wang.name Proxy会依次调用其中set(p.zhang , zhang.wang ....) ,若最后为赋值,则最后一次调用set
defineProperty
// 递归处理defineProperty多重嵌套的响应式处理,返回结果
function defineP(obj){
if(typeof obj !== "object"){
console.log("不是");
return obj
}
const target = Array.isArray(obj)?[]:{};
let keys = Object.keys(obj);
keys.forEach(key => {
if(typeof obj[key] !== "object"){
Object.defineProperty(target , key , {
get(){
console.log(`得到${obj[key]}`);
return obj[key];
},
set(value){
console.log(`set${value}`);
obj[key] = value;
}
})
}
else{
target[key] = defineP(obj[key])
}
});
return target
}
//递归处理绑定到指定obj
function defineP(obj , objUse){
if(typeof obj !== "object"){
Object.defineProperty(objUse , obj , {
get(){
console.log(`得到${obj}`);
return obj;
},
set(value){
console.log(`set${value}`);
obj = value
}
})
return
}
let keys = Object.keys(obj);
keys.forEach(key => {
if(typeof obj[key] !== "object"){
Object.defineProperty(objUse , key , {
get(){
console.log(`得到${obj[key]}`);
return obj[key];
},
set(value){
console.log(`set${value}`);
obj[key] = value;
}
})
}
else{
objUse[key] = Array.isArray(obj[key])?[]:{};
defineP(obj[key] , objUse[key])
}
});
}
结果
一种为工厂模式,直接返回结果,在外面接收
另一种为传入接收对象,绑定到指定对象身上