You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Proxy object is used to create a proxy for another object, which can intercept and redefine fundamental operations for that object such as property lookup, assignment, enumeration, function invocation etc. These are used in many libraries and some browser frameworks.
325
+
326
+
The proxy object is created with two parameters with below syntax,
327
+
328
+
```js
329
+
let proxy = new Proxy(target, handler)
330
+
```
331
+
332
+
1. **target:** Object on which you want to proxy
333
+
2. **handler:** An object that defines which operations will be intercepted and how to redefine them.
334
+
335
+
The property Lookup Behavior of a user proxied object will be as below,
336
+
337
+
```js
338
+
const target = {
339
+
name: "John",
340
+
age: 3
341
+
};
342
+
343
+
const handler = {
344
+
get: function(target, prop) {
345
+
return prop in target ?
346
+
target[prop] :
347
+
`${prop} does not exist';
348
+
}
349
+
};
350
+
351
+
constuser=newProxy(target, handler);
352
+
console.log(user.name); // John
353
+
console.log(user.age); // John
354
+
console.log(user.gender); // gender does not exist
355
+
```
356
+
357
+
These proxies also enforce value validations. Let's take an example with set handler,
358
+
359
+
```js
360
+
let ageValidator = {
361
+
set:function(obj, prop, value) {
362
+
if (prop ==='age') {
363
+
if (!Number.isInteger(value)) {
364
+
thrownewTypeError('The age is not an integer');
365
+
}
366
+
if (value >200) {
367
+
thrownewRangeError('Invalid age');
368
+
}
369
+
}
370
+
371
+
obj[prop] = value; // The default behavior to store the value
0 commit comments