不使用Reflect
const obj = {
a:1,
b:2,
get c(){
return this.a +this.b
}
}
const proxy = new Proxy(obj,{
get(target,key){
console.log('proxy get',key)
return target[key]
}
})
console.log(proxy.c) // proxy get c
上面例子讀取c的時候只打印 proxy get c
原因
proxy.c 讀取返回的是obj上的getter,此時this默認(rèn)是指向obj的
而不是代理對象,所以this.a this. b 的讀取沒有經(jīng)過代理對象,所以無法打印
使用Reflect
const obj = {
a:1,
b:2,
get c(){
return this.a +this.b
}
}
const proxy = new Proxy(obj,{
get(target,key){
console.log('proxy get',key)
return Reflect.get(target,key,proxy)
}
})
console.log(proxy.c)
// 打印
//proxy get c
//proxy get a
//proxy get b
使用Reflect后,執(zhí)行g(shù)et時的this會指向proxy
這時讀取a b就是過proxy的,就能達(dá)到監(jiān)聽的目的
Reflect的方法
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect
Reflect.apply(target, thisArgument, argumentsList)
Reflect.construct(target, argumentsList[, newTarget]) // 相當(dāng)于new
Reflect.defineProperty(target, propertyKey, attributes)
Reflect.deleteProperty(target, propertyKey)
Reflect.get(target, propertyKey[, receiver])
Reflect.getOwnPropertyDescriptor(target, propertyKey)
Reflect.getPrototypeOf(target)
Reflect.has(target, propertyKey)
Reflect.isExtensible(target)
Reflect.ownKeys(target)
Reflect.preventExtensions(target)
Reflect.set(target, propertyKey, value[, receiver])
Reflect.setPrototypeOf(target, prototype)
Reflect.get和直接獲取屬性的區(qū)別
const obj = {
a:1,
b:2,
get c(){
return this.a +this.b
},
}
obj.a // 調(diào)用[[GET]]
Reflect.get(obj, 'a')// 調(diào)用[[GET]] // 兩者目前沒區(qū)別
// 但是當(dāng)讀取的是函數(shù),就會有一點(diǎn)區(qū)別
obj.c // 先把this指向obj,再調(diào)用[[GET]]
Reflect.get(obj, 'c')// 直接調(diào)用[[GET]] 第三個參數(shù)receiver默認(rèn)是當(dāng)前obj
// 上面例子這兩個其實也沒區(qū)別
// 唯一一點(diǎn)區(qū)別只有Reflect可以干涉[[GET]]時this的設(shè)置
拓展問題:
和apply bind call改this有什么區(qū)別
const obj = {
a:1,
b:2,
get c(){
return this.a +this.b
},
d:function d(){
console.log(this)
return this.a +this.b
}
}
Reflect.get(obj,'d',{a:2,b:3}) // 只是獲取屬性
Reflect.get(obj,'d',{a:2,b:3})() // 會執(zhí)行d,打印的this是window
所以區(qū)別在于apply call bind是改的調(diào)用時的this
Reflect的receiver的設(shè)置會影響getter setter時的this,而不是調(diào)用時的this