What is a Proxy? What exactly does it do? Before explaining this, let’s look at a real-world example.

Each of us has a lot of things to do in our daily life, such as reading emails, receiving express delivery, and so on. There are times when we may feel a little anxious: there are a lot of spam emails on our mailing lists, and it takes a lot of time to sift through them; The delivery received may contain bombs planted by terrorists, threatening our security.

That’s when you might want a loyal housekeeper. You want the housekeeper to help you do the following: Have it check your inbox and remove all spam email before you start reading it; When you receive the package, have it check the package with professional equipment to make sure there is no bomb inside.

In the above example, the housekeeper is our proxy. While we were trying to do something, the housekeeper did something extra for us.

Now let’s go back to JavaScript. We know that JavaScript is an object-oriented programming language, and we can’t write code without objects. But JavaScript objects are always running naked, and you can do anything with them. Many times, this makes our code less secure.

So the Proxy feature introduced in ECMAScript2015. With Proxy, we can find a loyal housekeeper for the object and help us enhance the original functions of the object.

At the most basic level, the syntax for using Proxy looks something like this:

// This is a normal object
let obj = {a: 1, b:2}

// Configure obj with a housekeeper using Proxy
let objProxy = new Proxy(obj, handler)

This is just a hint of code. Because we haven’t written a handler yet, so this code won’t run correctly for the time being.

For a person, we might have operations like reading mail, picking up delivery, etc., and the housekeeper can do that for us. For an object, we may read properties, set properties, and so on, which can also be enhanced by the proxy object.

#javascript #proxy #web development

Why Proxy is a Gem in JavaScript?
20.55 GEEK