DEV Community

MR.H
MR.H

Posted on

Javascript Proxy

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
Enter fullscreen mode Exit fullscreen mode

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

Happy Coding

Top comments (0)