// 2.x 响应式原理
const oldArrayPrototyoe = Array.prototype;
// 继承 创建新的原型
const proto = Object.create(oldArrayPrototyoe);
['push', 'unshift', 'shift'].forEach(method => {
// 函数劫持,重新数组方法
proto[method] = function () {
oldArrayPrototyoe[method].call(this,...arguments)
updateView()
}
})
function observe(target) {
if(typeof target !== 'object' || target === null) {
return target
}
if(Array.isArray(target)) {
// 拦截数组方法,实现动态更新
Object.setPrototypeOf(target, proto)
}
Object.keys(target).forEach(key => {
defineReactive(target,key,target[key])
})
}
function defineReactive(target, key, value) {
// 递归,如果value 仍是对象
observe(value)
Object.defineProperty(target, key, {
get() {
// 这里可以进行,watch收集
return value
},
set(newValue) {
if(value !== newValue) {
value = newValue
updateView()
// 递归,newValue = {a: 1}
observe(newValue)
}
}
})
}
function updateView() {
console.log("视图更新");
}
let obj = {
name: 'xx',
age: [1,2,3],
}
observe(obj)
obj.age.push(4)
obj.name = {
a: 1
}
obj.name.a = 2
vue2.x 响应式原理
一个幽默的前端爱好者,记录下自己的心得体会