Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Javascript — Proxy and Reflect

Tags: proxy object trap

JavaScript : Proxy and Reflect

Proxy is a concept in javascript that is not so popular and most of us have not used it anywhere in our work, But it is good to know what it does and how to use it.

In this article, we will understand what is Proxy and how to create and use it

What is a proxy?

Proxy is an Object that will be created from another object(target object), Using this proxy object we can intercept/modify all the operations that are happening on the object

Creating a proxy

This is the syntax for creating a proxy

const proxy = new Proxy(target, handler);

target — is the object for which we want to create a proxy, it can be any sort of object, including a native array, a function, or even another proxy.

handler — is the object which contains all the traps (operations to intercept) on the object

What are traps?

traps are nothing but operations that we can intercept in the created proxy object.
Each trap will have a function as its value, and that function will be invoked when the intended operation for that trap happens.

If no trap is present for any operation means, then that operation will be directly performed on the target object itself.

List of traps

Let’s understand this more by creating a proxy object with a get trap,

const target = {
name: 'Alex',
age: 25,
}

const proxy = new Proxy(target, {
get: function(target, prop) {
console.log(prop + ' property accessed');
return 'value for ' + prop + ' is ' + target[prop];
},
});

const name = proxy.name; // name property accessed
console.log(name); // value for name is Alex

In the above example, the target is the object, for which we created our proxy, and we added a handler with a trap for get (trap to intercept property accessing),

As we can see from the get trap, the respective trap function will receive a few arguments, based on the type of trap, these arguments may differ, but all traps will receive the original target object as their first argument.

using this, we can perform all the operations that we want to do in the target object.

Let’s create another proxy for the same target with a different trap ,

const target = {
name: 'Alex',
age: 25,
}

const proxy = new Proxy(target, {
set: function(target, prop, value) {
if (prop === 'age' && typeof value !== 'number') {
throw new Error('Invalid type , Age must be an number')
}
console.log('Writing ' + prop + ' = ' + value);
target[prop] = value;
}
});



proxy.age = 100; // Writing age = 100
proxy.name = 'John' // Writing name = John
console.log(target); // { name: 'John', age: 100 }

proxy.age = '50' // Error: Invalid type , Age must be an number
console.log(target); // { name: 'John', age: 100 }

In the above example, we have added a trap for property writing and we added some validations inside our trap function.
so now our trap will throw an error if we try to add any value of type other than a number to the age property.

Below are the example with a few more traps,

const target = {
name: 'Alex',
age: 25,
}

const proxy = new Proxy(target, {

has: function(target, prop) {
console.log(' in keyword used ')
return true;
},

deleteProperty: function(target, prop) {
console.log('delete operator used')
},

});

console.log('name' in proxy); // in keyword used
delete proxy.a; // delete operator used

I believe you understood how to create a proxy object and intercept these operations on it, Now we will see what is Reflct and why it exists, and how it is related to proxy

What is Reflect?

Reflect is a global object which has only static methods which are the same as the proxy handler traps

It is similar to a Math object, it only has static methods and we cannot create any instance out of it.

The major use of Reflect is to provide a way to forward the operation that is happening inside the trap to the original target object.

consider the below get trap where we are reading the property directly from the target,

  get: function(target, prop) {
return target[prop];
}

It works perfectly, but it’s not a good idea to access the target directly inside trap methods, (check the reason here)

so we can use Reflect here and access the target object.

  get: function(target, prop) {
return Reflect.get(target, prop);
}

using Reflect will directly call the internal implementation of the respective method.

Some of the common use cases of proxies are

  • to implement custom behavior of any operation,
  • to log the actions happening on the object,
  • to validate & format the value,
  • to sanitize inputs before writing.

This is all about Proxy and Reflect in javascript, if you want to dive deep, you can read more from here.

I hope you learned something new today

Follow me on Linkedin and Medium for more such content.

Keep learning and keep coding!


Javascript — Proxy and Reflect was originally published in Enlear Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.



This post first appeared on Enlear Academy, please read the originial post: here

Share the post

Javascript — Proxy and Reflect

×

Subscribe to Enlear Academy

Get updates delivered right to your inbox!

Thank you for your subscription

×