Reflect 反射和Proxy 代理

前言

在閱讀了很多博文後,發現大部分博文都是先代理後反射,這樣來說對於一下我來說不是很友好,所以本篇博文將先記錄反射,在來記錄下代理將會更友好的閱讀。


JavaScript的編程思想是面對對象的思想和函數式編程的思想,二函數式編程的思想就是將所有的操作變爲函數操作,比如說 1 + 2 用函數式編程的思想的寫法

function add(a, b) {
    return a + b;
}

add(1,2);

Reflect 反射

Reflect 反射也就運用了函數式編程的思想,將以前的 new、delete 等等變成了一系列的方法,封裝到了 Reflect 對象中。

在這裏插入圖片描述

defineProperty() 設置對象的屬性描述

Object.defineProperty() 類似,不瞭解的可以去看我上一篇博文 Object 屬性描述符

deleteProperty() 移除對象的屬性

const obj = {
    a: 1,
    b: 2
}
// 使用前
delete obj.a;
// 使用 Reflect 
Reflect.deleteProperty(obj, "a")

// {b: 2}

apply() 調用函數

function fun(a, b) {
    return a + b;
}
// 使用前
fun(3,4)
// 使用 Reflect 
Reflect.apply(fun, null, [3, 4])
// 7

construct() 創建對象

function Test(a, b) {
    this.a = a;
    this.b = b;
}
// 使用前
const t = new Test(5,6)
// 使用 Reflect 
const t = Reflect.construct(Test, [5, 6])

// Test {a: 5, b: 6}

set() 獲取屬性

const obj = {
    a: 1,
    b: 2
}
// 使用前
obj.c = 10;
// 使用 Reflect 
Reflect.set(obj, "c", 10)

// obj => {a: 1, b: 2, c: 10}

get() 獲取屬性

const obj = {
    a: 1,
    b: 2
}
Reflect.get(obj, "a") // 1

getOwnPropertyDescriptor() 返回屬性描述符

const obj = {
    a: 1,
    b: 2
}

Reflect.getOwnPropertyDescriptor(obj, 'a')
// {value: 1, writable: true, enumerable: true, configurable: true}

setPrototypeOf() 設置指定對象的原型

const obj1 = {
    a: 1,
    b: 2
}
const obj2 = {
    a: 3,
    b: 4
}

Reflect.setPrototypeOf(obj1, obj2)
// obj1.__proto__ => {a: 3, b: 4}

getPrototypeOf() 返回指定對象的原型

const obj = {
    a: 1,
    b: 2
}
Reflect.getPrototypeOf(obj)

// obj.__proto__

has() 判斷對象是否擁有某個屬性

const obj = {
    a: 1,
    b: 2
}
// 使用前
console.log('a' in obj)
// 使用 Reflect 
console.log(Reflect.has(obj, "a"));

// true

isExtensible() 判斷一個對象是否可擴展

const obj = {
    a: 1,
    b: 2
}
// 使用前
Object.isExtensible(obj)
// 使用 Reflect 
Reflect.isExtensible(obj)

// true

ownKeys() 以數組的形式返回對象的鍵

const obj = {
    a: 1,
    b: 2
}

Reflect.ownKeys(obj)
// ["a", "b"]

preventExtensions() 阻止添加新屬性

const obj = {
    a: 1,
    b: 2
}

Reflect.preventExtensions(obj)
obj.c = 3;
console.log(obj)

// {a: 1, b: 2}

以上就是 Reflect 反射對象裏封裝的函數方法了,有了 Reflect 反射對象的瞭解接下來就要來說 Proxy 代理。

Proxy 代理

Proxy 代理提供了修改底層實現的方式,返回一個代理對象。

new Proxy(target,handler)
參數 描述
target 代理對象
handler 普通對象

通過結合 Proxy 代理,可以修改 Reflect 反射底層的代碼。

const obj = {
    a: 1,
    b: 2
}
const proxy = new Proxy(obj, {
    set(target, protertyKey, value) {
        console.log(`設置了${protertyKey}屬性,值爲${value}`);
        Reflect.set(target, protertyKey, value);
    },
    get(target, protertyKey) {
        console.log(`訪問了${protertyKey}屬性`);
        return Reflect.get(target, protertyKey)
    }
})

proxy.a // 訪問了a屬性
proxy.a = 10 // 設置了a屬性,值爲10
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章