Javascript Proxy
MR.H
Posted on April 5, 2023
The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
Example
const target = {
message1:'hello',
message2:'everyone'
};
const handler = {
get(target,prop,receiver){
const value = target[prop]
if(prop ==='message1') {
return value + ' world'
} else if(prop ==='message2'){
return 'Welcome '+ value
}
return value
}
}
const proxy = new Proxy(target,handler);
console.log(proxy.message1) // hello world
console.log(proxy.message2) //Welcome everyone
The proxy object takes 2 arguments target
which you want to create proxy and handler
which
In the above example we have implemented get
trap. This will intercept when you try to access the properties
If you have read this far please leave a like and share your thoughts in the comment section
๐ ๐ช ๐
๐ฉ
MR.H
Posted on April 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev 5 Best Reasons You Should Choose Microservices Architecture for Your Project
November 2, 2024