DEV Community

MR.H
MR.H

Posted on

4

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay