vue-响应式原理-Object.defineProperty监听数组和对象

function viewChange(type){
    console.log('update view:'+type)
}
const originalProto=Array.prototype
//Object.create()创建一个新对象,原型指向originalProto,扩展新方法不会影响原型
const arrayProto=Object.create(originalProto)//克隆Array的原型
const methodsToPatch=['push','pop','shift','unshift','splice','sort','reverse']
methodsToPatch.map(item=>{
    arrayProto[item]=function(){
        originalProto[item].apply(this,arguments)
        // originalProto[item].call(this,arguments)
        // Array.prototype.push.call(this,arguments)
        viewChange('array')
    }
})
function objDefineProperty(obj,key,val){
    arrObserver(val)
    Object.defineProperty(obj,key,{
        get(){
            return val
        },
        set(newVal){
            if(newVal!==val){
                val=newVal
                viewChange('object')
            }
        }
    })
}
function arrObserver(arr){
    if(typeof arr!=='object'||arr===null){
        return arr
    }
    if(Array.isArray(arr)){
        //Array.prototype.push=function(){...} 这么写会污染全局的Array原型
        arr.__proto__=arrayProto
        for(let i in arr){
            arrObserver(arr[i])
        }
    }else{
        for(let i in arr){
            objDefineProperty(arr,i,arr[i])
        }
    }
}

const arr=['aaa','bbb','ccc',[111]]
arrObserver(arr)
arr[0]='ddd'
arr.push('ddd')
arr[3].push(222)
const obj={
    name:'name',
    child:{
        name:'child name'
    }
}
arrObserver(obj)
obj.name='name1'
obj.child.name='child name 1'
console.log(arr)

猜你喜欢

转载自blog.csdn.net/ifmushroom/article/details/124198651
今日推荐