Proxy can be understood as a layer of “interception” before the target object. All external access to the object must pass this layer of interception. Therefore, Proxy provides a mechanism for filtering and rewriting external access

Interception operations supported by common proxies.

get(target, propKey, receiver): // Intercepts reading of object attributes, such as proxy.foo and proxy['foo']
set(target, propKey, value, receiver): // Intercepts the setting of object attributes, such as proxy.foo = v or proxy['foo'] = v, which returns a Boolean value.
has(target, propKey): // Intercepts the propKey in proxy operation, returning a Boolean value
Copy the code

The set method is used to intercept the assignment of an attribute. It can take four parameters: the target object, the attribute name, the attribute value, and the Proxy instance itself. The last parameter is optional

Interception of empty objects

var obj = new Proxy({}, { get: function (target, propKey, receiver) { console.log(`getting ${propKey}! `); return Reflect.get(target, propKey, receiver); }, set: function (target, propKey, value, receiver) { console.log(`setting ${propKey}! `); return Reflect.set(target, propKey, value, receiver); }});Copy the code

1. Throw an error if accessing properties of the target object that do not exist

Var person = {name: "name"}; var proxy = new Proxy(person, { get: function(target, propKey) { if (propKey in target) { return target[propKey]; } else { throw new ReferenceError("Prop name \"" + propKey + "\" does not exist."); }}}); Proxy. name // "John" proxy.age // Throws an errorCopy the code

2. Js allows arrays to support negative indexes

function createArray(... elements) { let handler = { get(target, propKey, receiver) { let index = Number(propKey); if (index < 0) { propKey = String(target.length + index); } return Reflect.get(target, propKey, receiver); }}; let target = []; target.push(... elements); return new Proxy(target, handler); } let arr = createArray('a', 'b', 'c'); arr[-1] // cCopy the code

3. Assuming that the Person object has an age attribute, which should be an integer not greater than 200, you can use Proxy to ensure that the age attribute value meets the requirements

let validator = { set: function(obj, prop, value) { if (prop === 'age') { if (! Number.isInteger(value)) { throw new TypeError('The age is not an integer'); } if (value > 200) { throw new RangeError('The age seems invalid'); // Obj [prop] = value; obj[prop] = value; return true; }}; let person = new Proxy({}, validator); person.age = 100; Person. Age // 100 person. Age = 'young' // personCopy the code