实现数组劫持
数组考虑性能原因没有用defineProperty对数组的每一项进行拦截,而是选择重写数组
( push,shift,pop,splice,unshift,sort,reverse) 方法
数组中如果是对象数据类型也会进行递归劫持
核心代码
let obj = {
name:'jw' ,
age:30,
n: {
num: 000,
n: [1,2,3,4,5,6]
}
};
// 创建新的数组的方法
let newArrayProto = Object.create(Array.prototype)
// 保存老的数组方法
let oldArrayProtot = Array.prototype;
['push','shift','pop','splice','unshift','sort','reverse'].forEach(method=>{
newArrayProto[method] = function( ...args){
oldArrayProto[method]。call(this,...args)
}
})
// 定义相应式函数
function defineReactive(target,key,value){
// 判断检测对象中是否有嵌套对象
observer(value)
object.defineProperty(target, key,{
get(){
return value
},
set(newValue){
if(value !== newValue){
value = newValue;
// 判断心智是否有是对象
observer(newValue)
}
}
})
}
// 定义观察函数
function observer(data){
// 如果不是对象或者数据为空,直接返回
if(typeof data !== "object" || typeof data == null){
return data
}
// 判断是否是数组
if(Array.isArray(data)){
data.__proto__ = newArrayProto
} else for(let key in data){
// 循环执行第一层数据
defineReactive(data, key , data[key])
}
}
observer(obj)
数组的缺点
数组的索引和长度变化是无法监控到的
更多详细内容,请微信搜索“前端爱好者
“, 戳我 查看 。