[JS Pattern] Proxy pattern

Share a single global insance throughout our application

Proxies are a powerful way to add control over the behavior of an object. A proxy can have various use-cases: it can help with validation, formatting, notifications, or debugging.

BUT....

Overusing the Proxy object or performing heavy operations on each handler method invocation can easily affect the performance fo your application negatively. It's best to not use proxies for performance-critical code.

 

Basic:

in getter and setter functions, the 'obj' points to original "person" object; 'prop' points to the prop we try to access ('name' & 'age').

复制代码
const person = {
  name: "Joe",
  age: 42,
  nationality: "Germany"
}

const personProxy = new Proxy(person, {
  get: (obj, prop) => {
    console.log(`The value of ${prop} is ${obj[prop]}`)
  },
  set: (obj, prop, value) => {
     console.log(`Changed ${prop} from ${obj[prop]} to ${value}`)
     obj[prop] = value;
     return true
  }
});

personProxy.name
personProxy.age = 45
复制代码
/*
The value of name is Joe 
Changed age from 42 to 45 
*/

 

A proxy can be useful to add validation.

复制代码
const personProxy = new Proxy(person, {
  get: (obj, prop) => {
    if (!obj[prop]) {
      console.log(`Humm.. this property doesn't seem to exist on the target object`)
    } else {
      console.log(`The value of ${prop} is ${obj[prop]}`)
    }
  },
  set: (obj, prop, value) => {
    if (prop === "age" && typeof value !== "number") {
      console.log(`Sorry, you can only pass numeric values for age.`)
    } else if(prop === "name" && value.length < 2) {
      console.log(`You need to provide a valid name.`)
    } else {
     console.log(`Changed ${prop} from ${obj[prop]} to ${value}`)
     obj[prop] = value;
    }
    return true
  }
});
复制代码

The proxy makes sure that we weren't modifying the person object with faulty values, which helps us keep our data pure!

 

Reflect

Javascript provides a built-in object call Reflect, which makes it easier for us to manipulate the target object when working with proxies.

复制代码
const personProxy = new Proxy(person, {
  get: (obj, prop) => {
    if (!Reflect.get(obj, prop)) {
      console.log(`Humm.. this property doesn't seem to exist on the target object`)
    } else {
      console.log(`The value of ${prop} is ${Reflect.get(obj, prop)}`)
    }
  },
  set: (obj, prop, value) => {
    if (prop === "age" && typeof value !== "number") {
      console.log(`Sorry, you can only pass numeric values for age.`)
    } else if(prop === "name" && value.length < 2) {
      console.log(`You need to provide a valid name.`)
    } else {
     console.log(`Changed ${prop} from ${obj[prop]} to ${value}`)
     // obj[prop] = value;
     Reflect.set(obj, prop, value)
    }
    return true
  }
});
复制代码

 

[Note]: from JS patterns book

posted @   Zhentiw  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-01-23 [AST Eslint] No console with schema options && isPrimitive
2020-01-23 [Javascript] Deep partial equal Object LooksLike
2020-01-23 [AST Eslint] No Console allowed
2020-01-23 [Algorithm] 234. Palindrome Linked List / Reverse linked list
2019-01-23 [Javascript] Write a Generator Function to Generate the Alphabet / Numbers
2019-01-23 [Javascript] Intercept property access with Javascript Proxy
2019-01-23 [Functional Programming 101] Crocks.js -- when to use map and when to use chain?
点击右上角即可分享
微信分享提示