[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