1. Proxy is used to modify the default behavior of certain operations, equivalent to making changes at the language level, so it belongs to a "meta-programming" (Meta programming) programming language.
2, the Proxy can be understood, before the target object to set up a layer of "interception", the external access to the object must first through this layer of interception, thus providing a mechanism, can be filtered and rewritten outside the access. The word proxy is intended to be an agent, which is used here to represent some operations by it to "proxy", which can be translated into "proxies".
3. The ES6 primitive provides a proxy constructor, which is used to generate a proxy instance.
var New Proxy (target, handler);
All usages of the Proxy object are in this form, excepthandlerThe notation of the parameter. whichnew Proxy()Represents the generation of aProxyInstancetargetParameter represents the target object to intercept,handlerThe parameter is also an object used to customize the interception behavior.
4. One technique is to set the Proxy object to a object.proxy property so that it can be object called on the object.
var New Proxy (target, Handler)};
5. The Get method is used to intercept the read operation of a property. The following is an example of an interception read operation.
varperson ={name:"Zhang San"};varProxy =NewProxy (person, {get:function(target, property) {if(Propertyinchtarget) { returnTarget[property]; } Else { Throw NewReferenceerror ("Property \" "+ Property +" \ "does not exist."); }});p Roxy.name//"Zhang San"Proxy.age//throws an error
6. The Set method is used to intercept the assignment operation of a property.
Let validator ={set:function(obj, prop, value) {if(prop = = = ' Age ') { if(!Number.isinteger (value)) { Throw NewTypeError (' The age isn't an integer '); } if(Value > 200) { Throw NewRangeerror (' The Age seems invalid '); } } //for attributes other than age, save directlyObj[prop] =value; }};let Person=NewProxy ({}, Validator);p Erson.age= 100;p erson.age// -Person.age = ' Young '//ErrorPerson.age = 300//Error
7. The Apply method intercepts the invocation, call, and apply operations of the function. The Apply method can accept three parameters, namely, the target object, the target object's context object (this), and the parameter array of the target object.
var twice = { apply (target, CTX, args) { return reflect.apply (... arguments) * 2; }}; function sum (left, right) { return left + right ;}; var New Proxy (sum, twice);p Roxy (// 6proxy.call (null// 22 proxy.apply (null// )
Js-es6 Learning Note-proxy