js 对象嵌套 hook

 

https://blog.csdn.net/weixin_54000091/article/details/125160977

 

    var obj={
                addr:'湖南',
                goods:{
                    fruits:[
                        {
                            name:'🍉',
                            price:12
                        },
                        {
                            name:'🍌',
                            price:11
                        }
                    ]
                },
                traffic:{
                    car:[
                        {
                            name:'🚗'
                        },
                        {
                            name:'🚓'
                        }
                    ]
                }
            }
            
    function observe(data,rootAttr,isRoot){
            for(let key in data){
                let val=data[key]
                Object.defineProperty(data,key,{
                    set(newval){
                            if(isRoot){
                                rootAttr=key
                            }
                            console.log(`监听到${rootAttr}设置`)
                        
                        val=newval
                    },
                    get(){
                        console.log('监听到读取')
                        return val
                    }
                })
                if(Object.prototype.toString.call(val)=='[object Object]'){
                    rootAttr=key
                    observe(val,rootAttr,false)
                }
            }
        }
        observe(obj,undefined,true)

 

posted @ 2022-07-01 22:58  AngDH  阅读(87)  评论(0编辑  收藏  举报