Day 9

Proxy and reflection

Basis of agency:

  • A proxy is an abstraction of the target object. It can be treated as a surrogate of the target object, but it is completely independent of the target object. The target object can be manipulated either directly or through a proxy

Create an empty proxy:

  • The simplest proxy is an empty proxy. That is, it does nothing but act as an abstract target object, and all operations performed by the proxy object are propagated to the target object without any barrier. Therefore, wherever the target object is used, the proxy object associated with it can be used in the same way

    Example 1:

const target = { id: 'target' };
const handler = {};
const proxy = new Proxy(target, handler);
// The id attribute accesses the same value
console.log(target.id); // target 
console.log(proxy.id); // target  // Assigning a value to the target property is reflected on both objects because both objects access the same value target.id = 'foo'; console.log(target.id); // foo console.log(proxy.id); // foo  // Assigning a proxy property is reflected on both objects because the assignment is transferred to the target object proxy.id = 'bar'; console.log(target.id); // bar console.log(proxy.id); // bar  // The hasOwnProperty() method applies to the target object in both places console.log(target.hasOwnProperty('id')); // true  console.log(proxy.hasOwnProperty('id')); // true Copy the code

Summary: This is the most simple agents in an empty case, at first glance may be unknown, so I had to look very meng, but don’t try so hard, now you just need to understand and know what did the agent, in this example, the target is a target for the proxy, the proxy agent, the agent of the target and the agent property sharing, sharing operation, including methods are Shared, However, the agent is not equal to the agent target. When it is more inclined to operate the agent, the agent forwards the operation to the agent target and then performs the operation. What the target owns, the agent owns, and what the agent owns, will be passed to the target accordingly.

Code catcher and reflection methods:

  • Is using a proxy “purpose” : can define “capture” (trap), can capture device is directly or indirectly on the proxy object call, every time they call these basic operations on the proxy objects, the agent can call first before these operations spread to the target object capture function, thus block section and modify the behavior of the corresponding.

    • In general terms, the catcher executes when the proxy object is called, intercepting and modifying the behavior of the object, which is a kind of if, or pop-up validation
  • “Handler” : the object that the agent handles. In example 1, this is an empty object. In most cases it is not an empty object, but one or more traps are defined to handle the agent.

  • “Set trap” : a common trap that is triggered when a property value is set.

  • “Reflect.set” : A function that assigns a value to an attribute. Returns a Boolean or true if the update was successful

    First set trap accepts four parameters,

    • TrapTarget – The object that receives the property, which is the target of the proxy

    • Key – the “key” of the property to be written

    • Value – the “value” of the property to write

    • Receiver – The object operated on, usually a “proxy”

      Example 2: Verify that the value of an attribute is number with a set trap

let target = {
       name: "target"
     };
     
     let proxy = new Proxy(target, {
 //target,name,target,proxy;  set(trapTarget, key, value, receiver) {  console.log(`trapTarget is ${trapTarget}, key is ${key}, value is ${value}, receiver is ${receiver}`)  // Ignore the attributes that exist, so as not to have any influence, and the attributes that do not exist will enter the judgment  if(! trapTarget.hasOwnProperty(key)) { // Check whether the value is number  if (isNaN(value)) {  throw new TypeError("Property must be a number.");  }  }  // Add to property  return Reflect.set(trapTarget, key, value, receiver);  }  });  // Add a new attribute  proxy.count = 1;  console.log(proxy.count); / / 1  console.log(target.count); / / 1  // Assign to the attribute that exists on the target  proxy.name = "proxy";  console.log(proxy.name); // "proxy"  console.log(target.name); // "proxy"  // If the new property value is not a number, an exception is thrown  proxy.anotherName = "proxy"; Copy the code
Summary: This example prints out the time changes of four parameters, and you can clearly see the corresponding values of the parameters. It can be found that the interception judgment will be made every time the property value is set, so you can use GET to intercept judgment when obtaining.Copy the code
  • Get Trap:

    • Get is a trap used to read an object property. It takes three parameters

    • TrapTarget: Specifies the object from which the properties are read

    • Key – The key that is read

    • Receiver – The object operated on, usually a proxy

      Example 1: This is the logic of a normal GET agent

     const handler = {
         get: function(obj, prop) {
             return prop in obj ? obj[prop] : 37;
         }
     };
  const p = new Proxy({}, handler);  p.a = 1;  p.b = undefined;   console.log(p.a, p.b); // 1, undefined  console.log('c' in p, p.c); // false, 37 Copy the code
P in p, p does not have a c attribute, so it returns false. P in p gets c attribute like p, goes to GET, and assigns the value 37.Copy the code
  • Let’s do a combination of set and get

    Example 3;

   var p = {
     name:"chen".     work:function() {
       console.log("wording...");
     },
 _age:18. // Listen for the event of the name attribute  get name(){  return this._age;  },  // Listen for events that set the age property  set age(val) {  if (val<0 || val> 100) {// Throw an error if the age is greater than 100  throw new Error("invalid value")  }else{  this._age = val;  }  }  };  console.log(p.name);// Output 18, which returns age because it triggers interception listening on the name property,  console.log(p._age);// Here the age is not intercepted, so output the original value  console.log(p._age =20);// Output 20, because here enter set interception, satisfy the condition, complete the assignment  console.log(p._age =200);// Error: set interception to enter, if the condition is not met, error  console.log(p.name = 'yu')// Output yu, which succeeds because name is not set to intercept Copy the code

Summary: after reading this, the basic knowledge of the agent and its principles believe that we all understand, in fact, there are many traps, such as has and so on, but the basic principles are like this, as long as the grasp of the parameters respectively represent what, the trigger condition of the trap, the problem can be solved, hope to bring help to you

This article was typeset using MDNICE