DEV Community

Delyce Twizeyimana
Delyce Twizeyimana

Posted on

PROXY PATTERN

What is a proxy.
A proxy is a stand-in for someone else, similar to JavaScript, instead of interacting with the target object directly, we'll interact with the Proxy object.

A proxy takes two arguments, the first is the object its representing whereas the second is the handler where all behaviors of how to interact with the target object are defined.

Additionally, there are two methods get() which is invoked when trying to access a property and set() which is invoked when trying to modify a property.

As the get() method takes two arguments, set() takes three, where the third is the value that you want to set

const person = {
    name: "Anonymous",
    age: 21
}

const handler = {
    get: (obj, prop) => {
        console.log(`hello`, obj[prop])
    },
    set: (obj, prop, value) => {
             console.log(`Changed ${prop} from ${obj[prop]} to ${value}`);
        obj[prop] = value

        }

    }
}

const personProxy = new Proxy(person, handler)
personProxy.name
personProxy.age = 23

Enter fullscreen mode Exit fullscreen mode

Not only proxies helping us to directly interact with our target object, it can also help us in validation in order to avoid changing the target object with wrong values.
for instance on set method we can have something like this:

set: (obj, prop, value) => {

        if(value < 20){
            console.log("Small value")
        }
        else{
             console.log(`Changed ${prop} from ${obj[prop]} to ${value}`);
        obj[prop] = value

        }

    }
Enter fullscreen mode Exit fullscreen mode

And user age won't accept any value less than 20

As you have seen above we are accessing or changing values using obj[props], However, there is Reflect built in method which makes it easier for us to manipulate the target object when working with proxies.

set: (obj, prop, value) => {
    console.log(`Changed ${prop} from ${obj[prop]} to ${value}`);
    Reflect.set(obj, prop, value);
  }
Enter fullscreen mode Exit fullscreen mode

Proxies are a powerful way to add control over the behavior of an object.

Top comments (0)