// 一、Object.defineProperty()
let count =2
let double = count * 2
let obj = {
count:2
}
function getDouble(val) {
return val*2
}
Object.defineProperty(obj,'count',{
get() {
return count
},
set(val) {
console.log(val) // 3
double = getDouble(val)
}
})
console.log(double) // 4
obj.count = 3
console.log(double) // 6
console.log('---------------------')
// 二、Proxy
let target = {} ;
proxy = new Proxy(target,{
// get拦截器
get(target,key) {
console.log(target,key) // {} age
return 30
},
// set拦截器
set(target,key,value) {
console.log(target,key,value) // {} name iu
target[key] = value
},
deleteProperty(target,key) {
console.log(target,key) // {'name':'iu' } name
return delete target[key]
}
})
proxy.age
proxy.name = 'iu'
console.log(target.name) // iu
delete proxy.name
console.log(target.name) // undefined
console.log('---------------')
// 三、Object get/set
let _val = 6
let double1 = getDouble(_val)
let count1 = {
get value() {
return _val
},
set value(val) {
console.log(val)
_val = val
double1 = getDouble(val)
}
}
count1.value = 2
console.log(double1)
console