How do I create a Proxy?

const proxiedObject = new Proxy(initialObj, handler);

Calling the Proxy constructor, new Proxy() , will return an object that has the values contained in initialObj but whose basic operations like get and set , now have some custom logic specified by the handler object.

Let’s take an example to understand this,

Now, if we had not made a Proxy Object, calling console.log(proxiedObj.name) on Line 14 would’ve logged “Foo Bar” to the console.

But now that we’ve made a Proxy, the get operation has some custom logic that we have defined on Line 3.

Calling console.log(proxiedObj.name) will now actually log “A value has been accessed” to the console!

To the careful eye, you’d notice that there are actually two logs in the console. “A value has been accessed” and undefined. Why? 🤔

The default implementation of the get operator is to return the value stored in that key in the Object. Since we overrode it to just log a statement, the value is never returned, and hence the console.log() statement on line14 logs undefined .

Let’s fix that!

The get operator takes two parameters — the object itself and the property being accessed.

Returning the property’s value

Returning the property’s value — Console Output

That’s better! 😄

This custom override that we provided for get is called a trap (loosely based on the concept of operating system traps). The handler object is basically an object with a set of traps that would trigger whenever an object property is being accessed.

Let’s add a trap for set as well. We’ll do the same thing — any time a value is set, we’ll log the property being modified, as well as the value being set for that key.

The set operator takes three arguments — the object, the property being accessed and the value being set for that property.

Adding a `set` trap

Here, the access being made at Line 18 will trigger the function defined at Line 6, which will log the property being accessed and the value being set.