ES6 ~ Proxy API - rohit120582sharma/Documentation GitHub Wiki
The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
We use proxies for the intention of blocking direct access to the target function or object.
There are 3 key terms we need to define before we proceed:
- handler — the placeholder object which contains the trap(s)
- traps — the method(s) that provide property access
- target — object which the proxy virtualizes
- https://hackernoon.com/introducing-javascript-es6-proxies-1327419ab413
- http://www.zsoltnagy.eu/es6-proxies-in-practice/
The proxy object has some traps, handling the access of the target. The traps are the same as the methods used in the Reflect API.
- apply
- construct
- defineProperty
- deleteProperty
- get
- getOwnPropertyDescriptor
- getPrototypeOf
- has
- isExtensible
- ownKeys
- preventExtensions
- set
- setPrototypeOf
let validator = {
set : (target, prop, value, receiver)=>{
if(prop==='age'){
if(!Number.isInteger(value)){
throw new TypeError('The age is not integer');
}
if(value >= 150){
throw new RangeError('The age seems invalid');
}
}
target[prop] = value;
return true;
}
};
let person = {
name: 'Rohit'
};
let proxy = new Proxy(person, validator);
console.log(proxy.name); // Rohit
proxy.age = 100;
console.log(proxy.age); // 100
proxy.age = 'young'; // The age is not integer
proxy.age = 300; // The age seems invalid
let handler = {
get : (target, prop, receiver)=>{
return (prop in target) ? target[prop] : `Prop doesn't exist`;
}
};
let obj = {
name: 'Rohit'
};
let proxy = new Proxy(obj, handler);
console.log(proxy.name); // Rohit
console.log(proxy.salary); // Prop doesn't exist