```
const data = {
obj: {
a: 1,
b: 2
}
}
let value = data.obj
Object.defineProperty(data, 'obj', {
get() {
//console.log('获取');
return value
},
set(val) {
if (val === value) {
return; //第三步
}
//console.log('赋值');
value = val
reder() //第二步
}
})
data.obj = 90; //第四步
console.log(data.obj)
//第一步
function reder() {
console.log('渲染')
}
```
```
let data = {
obj: {
a: 1,
b: 2
},
arr: [1, 2, 3]
}
//let value = data.obj
//data.obj = 90; //第四步
//console.log(data.obj)
//第一步
function reder() {
console.log('渲染')
}
//第五步
function defineReactive(data, key, value) {
observer(value) //第九步
Object.defineProperty(data, key, {
get() {
//console.log('获取');
return value
},
set(val) {
if (val === value) {
return; //第三步
}
//console.log('赋值');
value = val
reder() //第二步
}
})
}
const arrayProto = Array.prototype;
const arratMethods = Object.create(arrayProto);
['shift', 'unshift', 'splic', 'sort', 'pop', 'push', 'reverse'].forEach(method => {
arratMethods[method] = function() {
arrayProto[method].call(this, ...arguments);
reder();
}
})
//第六步
function observer(data) {
data.__proto__ = arratMethods;
if (Array.isArray(data)) {
return
}
if (typeof data === '') {
for (let key in data) {
defineReactive(data, key, date[key])
}
}
}
observer(data)
//第八步
data.obj = 90;
data.arr = 80;
// const oldPushFn = Array.prototype.push;
// Array.prototype.push = function() {
// oldPushFn.call(this, ...arguments)
// reder()
// }
//data.arr.push(1)
console.log(data.arr)
function $set(data, key, value) {
if (Array.isArray(data)) {
data.splice(key, 1, value)
return value;
}
defineReactive(data, key.value);
reder()
return value
}
```