A handler object offers a list of methods that serve as traps for a proxy.
These methods are optional and if a trap has not been defined, the default behavior is to forward the operation to the target.
Most common traps are for getters and setters.
The following example defined a trap for the get property accessor method:
const restaurant = { soda: 2, // www.j a v a2s . co m burger: 1 }; const restHandler = { get: function(target, property) { if (property in target && target[property] > 0) { target[property] -= 1; return `Enjoy your ${property}`; } return `Sorry, We are out of ${property}s!`; } }; const restProxy = new Proxy(restaurant, restHandler); console.log(restProxy.soda); // Enjoy your soda console.log(restProxy.soda); // Enjoy your soda console.log(restProxy.soda); // Sorry, We are out of sodas! console.log(restProxy.burger); // Enjoy your burger console.log(restProxy.burger); // Sorry, We are out of burgers!
Here, we have a restaurant object that contains the list and the quantities of available inventory.
We are using proxy to wrap the restaurant object, which enables us to intercept (or "trap") native operations of the restaurant object.
You can also intercept setter events.
const restaurant = { soda: 5 /* ww w. ja va 2 s . co m*/ }; const restHandler = { set: function(target, property, value) { target[property] = value; console.log(`${property} has been added to inventory`); } } const restProxy = new Proxy(restaurant, restHandler); restProxy.beer = 10; // beer has been added to inventory
In this example, we overwrite the set property accessor method, which overrides the default assignment.