Skip to content

Commit e7555e4

Browse files
committed
Add proxies feature for ES6
1 parent c6eb942 commit e7555e4

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

README.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,67 @@ console.log(logLevels.INFO, 'info message');
320320
console.log(Symbol('foo') === Symbol('foo')); // false
321321
console.log(Symbol.for('foo') === Symbol.for('foo')); // true
322322
```
323+
### Proxies
324+
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+
const user = new Proxy(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+
throw new TypeError('The age is not an integer');
365+
}
366+
if (value > 200) {
367+
throw new RangeError('Invalid age');
368+
}
369+
}
370+
371+
obj[prop] = value; // The default behavior to store the value
372+
373+
return true; // Indicate success
374+
}
375+
};
376+
377+
const person = new Proxy({}, validator);
378+
379+
person.age = 30;
380+
console.log(person.age); // 30
381+
person.age = 'old'; // Throws an exception
382+
person.age = 200; // Throws an exception
383+
```
323384
324385
### Promises
325386

0 commit comments

Comments
 (0)