vue響應式為什么使用Reflect

不使用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默認是指向obj的

而不是代理對象,所以this.a this. b 的讀取沒有經過代理對象,所以無法打印

使用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后,執行get時的this會指向proxy

這時讀取a b就是過proxy的,就能達到監聽的目的

Reflect的方法

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect

Reflect.apply(target, thisArgument, argumentsList)
Reflect.construct(target, argumentsList[, newTarget]) // 相當于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和直接獲取屬性的區別

const obj = {
    a:1,
    b:2,
    get c(){
        return this.a +this.b
    },
}

obj.a // 調用[[GET]]
Reflect.get(obj, 'a')// 調用[[GET]] // 兩者目前沒區別


// 但是當讀取的是函數,就會有一點區別
obj.c // 先把this指向obj,再調用[[GET]]
Reflect.get(obj, 'c')// 直接調用[[GET]] 第三個參數receiver默認是當前obj

// 上面例子這兩個其實也沒區別
// 唯一一點區別只有Reflect可以干涉[[GET]]時this的設置

拓展問題:

和apply bind call改this有什么區別

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})() // 會執行d,打印的this是window

所以區別在于apply call bind是改的調用時的this

Reflect的receiver的設置會影響getter setter時的this,而不是調用時的this

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容