JavaScript | Proxy() Object
The proxy object in JavaScript is used to define the custom behavior of fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
Syntax:
var p = new Proxy(target, handler);
Parameter: The proxy object accept two parameters as mentioned above and described below:
- target: A target object (can be any sort of object including a function, class, or even another proxy) to wrap with Proxy.
- handler: An object whose properties are functions which define the behavior of the proxy when an operation is performed on it.
Example:
<script> const Person = { Name: 'John Nash', Age: 25 }; const handler = { // target represents the Person while prop represents // proxy property. get: function(target, prop) { if (prop === 'FirstName') { return target.Name.split(' ')[0]; } if (prop === 'LastName') { return target.Name.split(' ').pop(); } else { return Reflect.get(target,prop); } } }; const proxy1 = new Proxy(Person, handler); document.write(proxy1 + "<br>"); // Though there is no Property as FirstName and LastName, // still we get them as if they were property not function. document.write(proxy1.FirstName + "<br>"); document.write(proxy1.LastName + "<br>"); </script> |
Output:
[object Object] John Nash
Note: The above code can be run directly in terminal provided NodeJs is installed, else run it in a HTML file by pasting the above in script tag and check the output in console of any web browser.
Recommended Posts:
- How to access an object having spaces in the object's key using JavaScript ?
- How to check a JavaScript Object is a DOM Object ?
- How to get the first key name of a JavaScript object ?
- Object.is( ) in JavaScript
- Map vs Object in JavaScript
- How to get a key in a JavaScript object by its value ?
- JavaScript | Object Constructors
- Object.freeze( ) in JavaScript
- How to add key/value pair to a JavaScript object?
- Rename object key in JavaScript
- JavaScript | Object Prototypes
- How to clone a JavaScript object?
- JavaScript | Object Methods
- JavaScript | Set object key by variable
- JavaScript | Object Accessors
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

