A proxy is a JavaScript object that customizes operations (i.e. getting a key, setting a key, etc.).
The following illustration goes over the syntax and defines some important terms:
When a non-existent key in an object is accessed, it normally returns undefined. However, suppose that we want to return a -1 instead.
Here is where the proxy object comes in:
// Creating an objectlet country = {name: 'Singapore', area: 721.5};// Creating a handlerlet handler = {// get is a trap. Recall that the target is the object to be proxied.get: function(target, prop){// if the prop that the user is looking for exists in that object, return the valueif(Object.keys(target).includes(prop)){return target[prop];} else{// return a -1 if the prop does not exist in the object.return -1;}}}// Creating a proxylet proxy = new Proxy(country, handler);// Now access the props using the proxyconsole.log(proxy.name);console.log(proxy.area);console.log("Looking up an invalid key with a proxy:",proxy.population);console.log("Looking up an invalid key without the proxy:", country.population);
Suppose that we need to enforce a condition so that the value associated with name
cannot be an empty string.
This can be done using a proxy:
// Creating an objectlet country = {name: 'Singapore', area: 721.5};// Creating a handlerlet handler = {// get is a trap. Recall that the target is the object to be proxied// and value is the value to be assigned.set: function(target, prop, value){// if the user is trying to assign a name to an empty string, then//display an error message.if(prop === 'name' && value === ""){console.log("name cannot be empty.")return -1;// else, the assignment can occur successfully.}else if (prop === 'name'){target[prop] = value;console.log("The value has been successfully assigned.")return 0;}}}// Creating a proxylet proxy = new Proxy(country, handler);// Now assign using the proxyproxy.name = "";proxy.name = "Thailand";
A proxy can be applied on a function as well.
// Creating a functionfunction greeting (greeter){return 'Hello from ' + greeter;}// Recall that the target is the object (function is also// an object) to the proxied. thisArgs is the this argument for the//call and args are the arguments passed to the function.let handler = {apply: function(target, thisArg, args){return target(args[0]) + '!';}}// Creating the proxylet proxy = new Proxy(greeting, handler);// Using the proxyconsole.log(proxy('Eduactive'));
For more information, refer to the official documentation.
Free Resources