What is Proxy in Javascript ?
Hi Everyone ,
Today let's discuss about Proxy in JavaScript and how we can use them in our code.?
The very first basic question is, What is a Proxy ??
It is a feature offered by JavaScript through which we can access the object through a surrogate.?
How to create a Proxy ?
We can create a Proxy using in-built Proxy Constructor
When a proxy constructor is invoked it expects two arguments, one is the Target Object. In this case, it is a 'scientist', and we need to pass an object as a second argument and let's analyze the second argument further because it makes the proxies more unique and powerful.
It works like a normal object. You can get and set values, like How you do it with a normal object but something else is going on behind the scenes. Let's investigate it.?
领英推荐
In the second argument, we can use methods, which are called Traps, and they are called certain actions are performed on objects.?
?In the above example, we have specified two traps, get and set. Whenever we try to access the property of the object, the get method is implicitly called and the same goes for the set method and we are trying to access a property called invention which is not present in the object , In those places instead of undefined, we can return custom values in those places like shown in the above example
We can also manipulate other traps, like apply and enumerate using the same method.
Uses
We can use a Proxy? to measure performance, logging, validation, and we can also auto-populate the object properties.?
Drawback
Proxies are not fast. If it is overused it will make your application sloppier, so you must test the performance of the code when you use a Proxy.
This is just a gist of the Proxy in JavaScript, let's discuss more about it in future articles.
Thanks for reading ,
Vijay