Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Proxy is a Proxy that creates an interception before accessing an object. Any operation that accesses the object passes through this interception.

ProxyWhat can be intercepted?

  • getPrototypeOf()

  • setPrototypeOf()

  • isExtensible()

  • preventExtensions()

  • getOwnPropertyDescriptor()

  • defineProperty()

  • has()

  • get()

  • set()

  • deleteProperty()

  • ownKeys()

  • apply()

  • construct()

The instance

The Proxy grammar

let proxy = new Proxy(target, handler);
Copy the code

This is how Proxy is used, all the usage is the above method, the difference is that the handler intercepts the Settings

New Proxy() generates a Proxy instance

Target Indicates the target object to intercept

Handler is an object used to customize interception methods

You want tohandlerThe interception method is valid, all subsequent operations must be usedProxyAn instance of the

get

The GET method is probably the most used method in daily development, so let’s take a look at the scenario without Proxy

let user = {
  name: "Zhang"};console.log(user.name); / / zhang SAN
console.log(user.age); //undefined
Copy the code

Run the code

In the above code, an object is defined using let and has a name attribute

The name and age properties are then printed, and it is clear that the age property is not defined to print undefined

But in a real project we don’t want to return undefined to the page, so let’s see how we can use Proxy to solve this problem

let handler = {
  // Defines the interceptor for the get method
  get: function (target, key) {
    //target: the object to intercept
    //key: modified attribute
      if(target.hasOwnProperty(key)){
          if(key=='name') {return "Outlaw maniac." - Jack Three.}}return "18"}};let obj = {
  name: "Zhang"
};
let user = new Proxy(obj, handler);

// Note that the user object is not the user object of the previous example, but an instance of Proxy
console.log(user.name); // The outlaw fanatics - Zhang SAN

console.log(user.age); / / 18

Copy the code

Run the code

When we use Proxy, everything is different because we set the get method to intercept. When we get the name attribute, we return a fixed value, otherwise we return age 18.

This is not very rigorous, the actual project can not only have two fields, here is just for demonstration

You want tohandlerThe interception method is valid, all subsequent operations must be usedProxyAn instance of the

To verify this statement, let’s not use a Proxy instance and see what happens

Run the code

set

In actual projects, we often modify the attributes of an object. Sometimes, in some special scenarios, we need to judge whether the new attributes of the object are consistent with the current business scenario.

let user = new Proxy({age: 18
},
{
  set: function (target, key, value) {
    if (value > 140) {
      throw "You're going to be a fairy!";
    }
    target[key]=value
  }
}
);
user.age = 20;
console.log(user.age)/ / 20
user.age=200
//Uncaught You will become a fairy!
Copy the code

Run the code

When we modify a person’s age to be greater than 140, an exception is triggered

construct

The construct method intercepts the new operator. In order for the new operator to work on the generated Proxy object, the target object used to initialize the Proxy must have the construct internal method itself

The sample

let proxy = new Proxy(1, {
 construct(target, args) {
   console.log(target);
   return new target(...args);
 }
});

//Uncaught TypeError: Cannot create proxy with a non-object as target or handler 
Copy the code

Run the code


let proxy = new Proxy(function () {}, {
 construct(target, args) {
   console.log(args);
   return 1; }});let obj = new proxy();
//Uncaught TypeError: 'construct' on proxy: trap returned non-object ('1') 
Copy the code

Run the code

Here are two examples of errors. Here is a correct one

var p = new Proxy(function() {}, {
 construct: function(target, argumentsList, newTarget) {
   console.log('called: ' + argumentsList.join(', '));
   return { value: argumentsList[0] * 10}; }});console.log(new p(1).value); // "called: 1"
                            / / 10
Copy the code

Run the code

Draw conclusions from the above code

  • The object to be proxied must haveConstructmethods
  • You must return an object

other

Other methods continue in the next chapter