首頁>技術>

今天簡單介紹幾個工作中可以使用的Proxy案例。希望對大家有幫助,需要的時候可以使用,但是不提倡亂用。

Proxy 處理器get和set的介紹
//movie is a targetconst movie = {    name: "Pulp Fiction",    director: "Quentin Tarantino"};//this is a handlerconst handler = {    //get is a trap    get: (target, prop) => {        if (prop === 'director') {            return 'God'        }        return target[prop]    },    set: function (target, prop, value) {        if (prop === 'actor') {            target[prop] = 'John Travolta'        } else {            target[prop] = value        }    }};const movieProxy = new Proxy(movie, handler);console.log(movieProxy.director); //GodmovieProxy.actor = "Tim Roth";movieProxy.actress = "Uma Thurman";console.log(movieProxy.actor); //John Travoltaconsole.log(movieProxy.actress); //Uma Thurman
應用一 驗證屬性賦值
const handler = {    set: function (target, prop, value) {        const houses = ['Stark', 'Lannister'];        if (prop === 'house' && !(houses.includes(value))) {            throw new Error(`House ${value} does not belong to allowed ${houses}`)        }        target[prop] = value    }};const gotCharacter = new Proxy({}, handler);gotCharacter.name = "Jamie";gotCharacter.house = "Lannister";console.log(gotCharacter);gotCharacter.name = "Oberyn";gotCharacter.house = "Martell";
應用二 根據定義和狀態實現功能,例如傳送郵件
const sendEmail = () => {    console.log("haorooms test status 是complete 的發郵件")};const handler = {    set: function (target, prop, value) {        if (prop === 'status' && value === 'complete') {            sendEmail()        }        target[prop] = value    }};const tasks = new Proxy({}, handler);tasks.status = "complete";
應用三 設定資料快取和超時
const cacheTarget = (target, ttl = 60) => {    const CREATED_AT = Date.now();    const isExpired = () => (Date.now() - CREATED_AT) > (ttl * 1000);    const handler = {        get: (target, prop) => isExpired() ? undefined : target[prop]    };    return new Proxy(target, handler)};const cache = cacheTarget({age: 25}, 5);console.log(cache.age);setTimeout(() => {    console.log(cache.age)}, 6 * 1000);

結果:

25undefined

也就是在5秒之內可以返回,超時不返回。

缺點

雖然Proxy具備一些很神奇的功能, 但在使用時仍然具有一些不得不小心應對的限制:

效能會受到顯著的影響. 在注重效能的程式碼中應該避免對Proxy的使用

沒有辦法區分判斷一個物件是一個Proxy的物件或者是target的物件

Proxy可能會導致程式碼在可讀性上面出現問題

3
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • RobotFramework正式釋出4.0版本!!!