ES6系列之Proxy

原文鏈接 http://blog.poetries.top/2018/12/21/es6-proxy/

關(guān)注公眾號(hào)獲取更多資訊

一、proxy概述

Proxy的兼容性

image.png

proxy在目標(biāo)對(duì)象的外層搭建了一層攔截,外界對(duì)目標(biāo)對(duì)象的某些操作,必須通過(guò)這層攔截

var proxy = new Proxy(target, handler);

new Proxy()表示生成一個(gè)Proxy實(shí)例,target參數(shù)表示所要攔截的目標(biāo)對(duì)象,handler參數(shù)也是一個(gè)對(duì)象,用來(lái)定制攔截行為

var target = {
   name: 'poetries'
 };
 var logHandler = {
   get: function(target, key) {
     console.log(`${key} 被讀取`);
     return target[key];
   },
   set: function(target, key, value) {
     console.log(`${key} 被設(shè)置為 ${value}`);
     target[key] = value;
   }
 }
 var targetWithLog = new Proxy(target, logHandler);
 
 targetWithLog.name; // 控制臺(tái)輸出:name 被讀取
 targetWithLog.name = 'others'; // 控制臺(tái)輸出:name 被設(shè)置為 others
 
 console.log(target.name); // 控制臺(tái)輸出: others
  • targetWithLog 讀取屬性的值時(shí),實(shí)際上執(zhí)行的是 logHandler.get :在控制臺(tái)輸出信息,并且讀取被代理對(duì)象 target 的屬性。
  • targetWithLog 設(shè)置屬性值時(shí),實(shí)際上執(zhí)行的是 logHandler.set :在控制臺(tái)輸出信息,并且設(shè)置被代理對(duì)象 target 的屬性的值
// 由于攔截函數(shù)總是返回35,所以訪問(wèn)任何屬性都得到35
var proxy = new Proxy({}, {
  get: function(target, property) {
    return 35;
  }
});

proxy.time // 35
proxy.name // 35
proxy.title // 35

Proxy 實(shí)例也可以作為其他對(duì)象的原型對(duì)象

var proxy = new Proxy({}, {
  get: function(target, property) {
    return 35;
  }
});

let obj = Object.create(proxy);
obj.time // 35

proxy對(duì)象是obj對(duì)象的原型,obj對(duì)象本身并沒(méi)有time屬性,所以根據(jù)原型鏈,會(huì)在proxy對(duì)象上讀取該屬性,導(dǎo)致被攔截

Proxy的作用

對(duì)于代理模式 Proxy 的作用主要體現(xiàn)在三個(gè)方面

  • 攔截和監(jiān)視外部對(duì)對(duì)象的訪問(wèn)
  • 降低函數(shù)或類(lèi)的復(fù)雜度
  • 在復(fù)雜操作前對(duì)操作進(jìn)行校驗(yàn)或?qū)λ栀Y源進(jìn)行管理

二、Proxy所能代理的范圍--handler

實(shí)際上 handler 本身就是ES6所新設(shè)計(jì)的一個(gè)對(duì)象.它的作用就是用來(lái) 自定義代理對(duì)象的各種可代理操作 。它本身一共有13中方法,每種方法都可以代理一種操作.其13種方法如下

// 在讀取代理對(duì)象的原型時(shí)觸發(fā)該操作,比如在執(zhí)行 Object.getPrototypeOf(proxy) 時(shí)。
handler.getPrototypeOf()

// 在設(shè)置代理對(duì)象的原型時(shí)觸發(fā)該操作,比如在執(zhí)行 Object.setPrototypeOf(proxy, null) 時(shí)。
handler.setPrototypeOf()

 
// 在判斷一個(gè)代理對(duì)象是否是可擴(kuò)展時(shí)觸發(fā)該操作,比如在執(zhí)行 Object.isExtensible(proxy) 時(shí)。
handler.isExtensible()

 
// 在讓一個(gè)代理對(duì)象不可擴(kuò)展時(shí)觸發(fā)該操作,比如在執(zhí)行 Object.preventExtensions(proxy) 時(shí)。
handler.preventExtensions()

// 在獲取代理對(duì)象某個(gè)屬性的屬性描述時(shí)觸發(fā)該操作,比如在執(zhí)行 Object.getOwnPropertyDescriptor(proxy, "foo") 時(shí)。
handler.getOwnPropertyDescriptor()

 
// 在定義代理對(duì)象某個(gè)屬性時(shí)的屬性描述時(shí)觸發(fā)該操作,比如在執(zhí)行 Object.defineProperty(proxy, "foo", {}) 時(shí)。
andler.defineProperty()

 
// 在判斷代理對(duì)象是否擁有某個(gè)屬性時(shí)觸發(fā)該操作,比如在執(zhí)行 "foo" in proxy 時(shí)。
handler.has()

// 在讀取代理對(duì)象的某個(gè)屬性時(shí)觸發(fā)該操作,比如在執(zhí)行 proxy.foo 時(shí)。
handler.get()

 
// 在給代理對(duì)象的某個(gè)屬性賦值時(shí)觸發(fā)該操作,比如在執(zhí)行 proxy.foo = 1 時(shí)。
handler.set()

// 在刪除代理對(duì)象的某個(gè)屬性時(shí)觸發(fā)該操作,比如在執(zhí)行 delete proxy.foo 時(shí)。
handler.deleteProperty()

// 在獲取代理對(duì)象的所有屬性鍵時(shí)觸發(fā)該操作,比如在執(zhí)行 Object.getOwnPropertyNames(proxy) 時(shí)。
handler.ownKeys()

// 在調(diào)用一個(gè)目標(biāo)對(duì)象為函數(shù)的代理對(duì)象時(shí)觸發(fā)該操作,比如在執(zhí)行 proxy() 時(shí)。
handler.apply()

 
// 在給一個(gè)目標(biāo)對(duì)象為構(gòu)造函數(shù)的代理對(duì)象構(gòu)造實(shí)例時(shí)觸發(fā)該操作,比如在執(zhí)行new proxy() 時(shí)。
handler.construct()

三、Proxy場(chǎng)景

3.1 實(shí)現(xiàn)私有變量

var target = {
   name: 'poetries',
   _age: 22
}

var logHandler = {
  get: function(target,key){
    if(key.startsWith('_')){
      console.log('私有變量age不能被訪問(wèn)')
      return false
    }
    return target[key];
  },
  set: function(target, key, value) {
     if(key.startsWith('_')){
      console.log('私有變量age不能被修改')
      return false
    }
     target[key] = value;
   }
} 
var targetWithLog = new Proxy(target, logHandler);
 
// 私有變量age不能被訪問(wèn)
targetWithLog.name; 
 
// 私有變量age不能被修改
targetWithLog.name = 'others'; 

在下面的代碼中,我們聲明了一個(gè)私有的 apiKey,便于 api 這個(gè)對(duì)象內(nèi)部的方法調(diào)用,但不希望從外部也能夠訪問(wèn) api._apiKey

var api = {  
    _apiKey: '123abc456def',
    /* mock methods that use this._apiKey */
    getUsers: function(){}, 
    getUser: function(userId){}, 
    setUser: function(userId, config){}
};

// logs '123abc456def';
console.log("An apiKey we want to keep private", api._apiKey);

// get and mutate _apiKeys as desired
var apiKey = api._apiKey;  
api._apiKey = '987654321';

很顯然,約定俗成是沒(méi)有束縛力的。使用 ES6 Proxy 我們就可以實(shí)現(xiàn)真實(shí)的私有變量了,下面針對(duì)不同的讀取方式演示兩個(gè)不同的私有化方法。第一種方法是使用 set / get 攔截讀寫(xiě)請(qǐng)求并返回 undefined:

let api = {  
    _apiKey: '123abc456def',
    getUsers: function(){ }, 
    getUser: function(userId){ }, 
    setUser: function(userId, config){ }
};

const RESTRICTED = ['_apiKey'];
api = new Proxy(api, {  
    get(target, key, proxy) {
        if(RESTRICTED.indexOf(key) > -1) {
            throw Error(`${key} is restricted. Please see api documentation for further info.`);
        }
        return Reflect.get(target, key, proxy);
    },
    set(target, key, value, proxy) {
        if(RESTRICTED.indexOf(key) > -1) {
            throw Error(`${key} is restricted. Please see api documentation for further info.`);
        }
        return Reflect.get(target, key, value, proxy);
    }
});

// 以下操作都會(huì)拋出錯(cuò)誤
console.log(api._apiKey);
api._apiKey = '987654321';  

第二種方法是使用 has 攔截 in 操作

var api = {  
    _apiKey: '123abc456def',
    getUsers: function(){ }, 
    getUser: function(userId){ }, 
    setUser: function(userId, config){ }
};

const RESTRICTED = ['_apiKey'];
api = new Proxy(api, {  
    has(target, key) {
        return (RESTRICTED.indexOf(key) > -1) ?
            false :
            Reflect.has(target, key);
    }
});

// these log false, and `for in` iterators will ignore _apiKey
console.log("_apiKey" in api);

for (var key in api) {  
    if (api.hasOwnProperty(key) && key === "_apiKey") {
        console.log("This will never be logged because the proxy obscures _apiKey...")
    }
}

3.2 抽離校驗(yàn)?zāi)K

讓我們從一個(gè)簡(jiǎn)單的類(lèi)型校驗(yàn)開(kāi)始做起,這個(gè)示例演示了如何使用 Proxy 保障數(shù)據(jù)類(lèi)型的準(zhǔn)確性

let numericDataStore = {  
    count: 0,
    amount: 1234,
    total: 14
};

numericDataStore = new Proxy(numericDataStore, {  
    set(target, key, value, proxy) {
        if (typeof value !== 'number') {
            throw Error("Properties in numericDataStore can only be numbers");
        }
        return Reflect.set(target, key, value, proxy);
    }
});

// 拋出錯(cuò)誤,因?yàn)?"foo" 不是數(shù)值
numericDataStore.count = "foo";

// 賦值成功
numericDataStore.count = 333;

如果要直接為對(duì)象的所有屬性開(kāi)發(fā)一個(gè)校驗(yàn)器可能很快就會(huì)讓代碼結(jié)構(gòu)變得臃腫,使用 Proxy 則可以將校驗(yàn)器從核心邏輯分離出來(lái)自成一體

function createValidator(target, validator) {  
    return new Proxy(target, {
        _validator: validator,
        set(target, key, value, proxy) {
            if (target.hasOwnProperty(key)) {
                let validator = this._validator[key];
                if (!!validator(value)) {
                    return Reflect.set(target, key, value, proxy);
                } else {
                    throw Error(`Cannot set ${key} to ${value}. Invalid.`);
                }
            } else {
                throw Error(`${key} is not a valid property`)
            }
        }
    });
}

const personValidators = {  
    name(val) {
        return typeof val === 'string';
    },
    age(val) {
        return typeof age === 'number' && val > 18;
    }
}
class Person {  
    constructor(name, age) {
        this.name = name;
        this.age = age;
        return createValidator(this, personValidators);
    }
}

const bill = new Person('Bill', 25);

// 以下操作都會(huì)報(bào)錯(cuò)
bill.name = 0;  
bill.age = 'Bill';  
bill.age = 15;  

通過(guò)校驗(yàn)器和主邏輯的分離,你可以無(wú)限擴(kuò)展 personValidators 校驗(yàn)器的內(nèi)容,而不會(huì)對(duì)相關(guān)的類(lèi)或函數(shù)造成直接破壞。更復(fù)雜一點(diǎn),我們還可以使用 Proxy 模擬類(lèi)型檢查,檢查函數(shù)是否接收了類(lèi)型和數(shù)量都正確的參數(shù)

let obj = {  
    pickyMethodOne: function(obj, str, num) { /* ... */ },
    pickyMethodTwo: function(num, obj) { /*... */ }
};

const argTypes = {  
    pickyMethodOne: ["object", "string", "number"],
    pickyMethodTwo: ["number", "object"]
};

obj = new Proxy(obj, {  
    get: function(target, key, proxy) {
        var value = target[key];
        return function(...args) {
            var checkArgs = argChecker(key, args, argTypes[key]);
            return Reflect.apply(value, target, args);
        };
    }
});

function argChecker(name, args, checkers) {  
    for (var idx = 0; idx < args.length; idx++) {
        var arg = args[idx];
        var type = checkers[idx];
        if (!arg || typeof arg !== type) {
            console.warn(`You are incorrectly implementing the signature of ${name}. Check param ${idx + 1}`);
        }
    }
}

obj.pickyMethodOne();  
// > You are incorrectly implementing the signature of pickyMethodOne. Check param 1
// > You are incorrectly implementing the signature of pickyMethodOne. Check param 2
// > You are incorrectly implementing the signature of pickyMethodOne. Check param 3

obj.pickyMethodTwo("wopdopadoo", {});  
// > You are incorrectly implementing the signature of pickyMethodTwo. Check param 1

// No warnings logged
obj.pickyMethodOne({}, "a little string", 123);  
obj.pickyMethodOne(123, {});

3.3 訪問(wèn)日志

對(duì)于那些調(diào)用頻繁、運(yùn)行緩慢或占用執(zhí)行環(huán)境資源較多的屬性或接口,開(kāi)發(fā)者會(huì)希望記錄它們的使用情況或性能表現(xiàn),這個(gè)時(shí)候就可以使用 Proxy 充當(dāng)中間件的角色,輕而易舉實(shí)現(xiàn)日志功能

let api = {  
    _apiKey: '123abc456def',
    getUsers: function() { /* ... */ },
    getUser: function(userId) { /* ... */ },
    setUser: function(userId, config) { /* ... */ }
};

function logMethodAsync(timestamp, method) {  
    setTimeout(function() {
        console.log(`${timestamp} - Logging ${method} request asynchronously.`);
    }, 0)
}

api = new Proxy(api, {  
    get: function(target, key, proxy) {
        var value = target[key];
        return function(...arguments) {
            logMethodAsync(new Date(), key);
            return Reflect.apply(value, target, arguments);
        };
    }
});

api.getUsers();

3.4 預(yù)警和攔截

假設(shè)你不想讓其他開(kāi)發(fā)者刪除 noDelete 屬性,還想讓調(diào)用 oldMethod 的開(kāi)發(fā)者了解到這個(gè)方法已經(jīng)被廢棄了,或者告訴開(kāi)發(fā)者不要修改 doNotChange 屬性,那么就可以使用 Proxy 來(lái)實(shí)現(xiàn)

let dataStore = {  
    noDelete: 1235,
    oldMethod: function() {/*...*/ },
    doNotChange: "tried and true"
};

const NODELETE = ['noDelete'];  
const NOCHANGE = ['doNotChange'];
const DEPRECATED = ['oldMethod'];  

dataStore = new Proxy(dataStore, {  
    set(target, key, value, proxy) {
        if (NOCHANGE.includes(key)) {
            throw Error(`Error! ${key} is immutable.`);
        }
        return Reflect.set(target, key, value, proxy);
    },
    deleteProperty(target, key) {
        if (NODELETE.includes(key)) {
            throw Error(`Error! ${key} cannot be deleted.`);
        }
        return Reflect.deleteProperty(target, key);

    },
    get(target, key, proxy) {
        if (DEPRECATED.includes(key)) {
            console.warn(`Warning! ${key} is deprecated.`);
        }
        var val = target[key];

        return typeof val === 'function' ?
            function(...args) {
                Reflect.apply(target[key], target, args);
            } :
            val;
    }
});

// these will throw errors or log warnings, respectively
dataStore.doNotChange = "foo";  
delete dataStore.noDelete;  
dataStore.oldMethod();

3.5 過(guò)濾操作

某些操作會(huì)非常占用資源,比如傳輸大文件,這個(gè)時(shí)候如果文件已經(jīng)在分塊發(fā)送了,就不需要在對(duì)新的請(qǐng)求作出相應(yīng)(非絕對(duì)),這個(gè)時(shí)候就可以使用 Proxy 對(duì)當(dāng)請(qǐng)求進(jìn)行特征檢測(cè),并根據(jù)特征過(guò)濾出哪些是不需要響應(yīng)的,哪些是需要響應(yīng)的。下面的代碼簡(jiǎn)單演示了過(guò)濾特征的方式,并不是完整代碼,相信大家會(huì)理解其中的妙處

let obj = {  
    getGiantFile: function(fileId) {/*...*/ }
};

obj = new Proxy(obj, {  
    get(target, key, proxy) {
        return function(...args) {
            const id = args[0];
            let isEnroute = checkEnroute(id);
            let isDownloading = checkStatus(id);      
            let cached = getCached(id);

            if (isEnroute || isDownloading) {
                return false;
            }
            if (cached) {
                return cached;
            }
            return Reflect.apply(target[key], target, args);
        }
    }
});

3.6 中斷代理

Proxy 支持隨時(shí)取消對(duì) target 的代理,這一操作常用于完全封閉對(duì)數(shù)據(jù)或接口的訪問(wèn)。在下面的示例中,我們使用了 Proxy.revocable 方法創(chuàng)建了可撤銷(xiāo)代理的代理對(duì)象:

let sensitiveData = { username: 'devbryce' };
const {sensitiveData, revokeAccess} = Proxy.revocable(sensitiveData, handler);
function handleSuspectedHack(){  
    revokeAccess();
}

// logs 'devbryce'
console.log(sensitiveData.username);
handleSuspectedHack();
// TypeError: Revoked
console.log(sensitiveData.username);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容