-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-defineProperty.js
52 lines (47 loc) · 1.04 KB
/
01-defineProperty.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function defineReactive(obj, key, val) {
observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
console.log(`get ${key} value: ${val}`)
return val
},
set(newVal) {
console.log(`set ${key} value: ${newVal}`)
if (newVal !== val) {
val = newVal
}
if (newVal !== null && typeof newVal === 'object') {
defineReactive(obj, key, newVal)
}
}
})
}
function observe(obj) {
if (typeof obj !== 'object' || obj === null) {
return
}
Object.keys(obj).forEach(key => {
defineReactive(obj, key, obj[key])
})
}
const obj = { name: 'zqguo', age: 11, info: { orderId: 1 } }
observe(obj)
obj.name
obj.name = 'rick'
obj.name
obj.age
console.log('-------------------')
obj.info
obj.info.orderId
obj.info.orderId = 2
// console.log(obj.info.orderId)
// obj.info.foo = 'bar'
defineReactive(obj, 'gender', 'male')
obj.gender = 'male'
console.log('-------------------')
obj.info = { pid: 123 }
obj.info.pid
obj.info.pid = 21321
obj.info.pid