Detailed explanation of the principle of js Proxy

Detailed explanation of the principle of js Proxy

What is Proxy Mode?

Introducing a real-life example

As users, do we need to figure out a series of tedious things like how to evaluate the quality of a house, how to go through housing procedures, etc.? Obviously, users would not want to do this. What users care about most is the result. Users can get a satisfactory house by making demands on the house and providing money of equal value. This is the result.

So who will solve the tedious house-buying process for users? Of course it’s the “real estate agent”! The role of a real estate agency is to provide evaluation, transaction, agency, consulting and other services as well as after-sales services for the transaction objects in the supply and demand market of real estate development, operation and consumption.

Understand the definition of the proxy model with examples

In some cases, it is not appropriate or possible for one object to directly reference another object, and a proxy object can act as an intermediary between the client and the target object.

The agency model is to provide a kind of agent for other users. Users do not need to know the specific process of buying a house. What users should care about is how to get satisfactory results. What the agent needs to do is to complete the process of buying a house.

What is a Proxy

Proxy supports many interception operations, currently only get(target, propKey, receiver) and set(target, propKey, value, receiver) are mentioned.

  • Get method: intercepts the reading of object attributes;
  • set method: intercept the setting of object properties.

get(target, propKey, receiver)

Define a Person object, which will be proxied by Proxy. The outside world accesses the Person object through the Proxy instance object.

var person = {
    name: "kongsam",
    age: 21,
    hobbies:
        "Watching anime",
        "Cycling",
        "Play games"
    ]
}

Instantiate a Proxy object to intercept external operations on the Person object.

var proxy = new Proxy(person, {
    get: function (target, property) {
          // Print target and property to see what is inside.
          console.log("target = ", target);
          console.log("property = ", property);
          // Determine whether the object attribute accessed by the outside world exists in the target object.
          if (property in target) {
                return target[property];
          } else {
                // If the object property accessed by the outside world does not exist in the target object, an exception is thrown.
                throw new ReferenceError('Property "' + property + '" does not exist.');
          }
    },
});

When performing the proxy.name operation, since the Person object has been proxied by Proxy, whenever I access the attributes existing in Person through the Proxy instance object, the get method will be called, and the get method intercepts the reading of the object attributes.

The information received by the two parameters target and property in get: function (target, property) is shown in the figure

There will be no exception when accessing the properties that exist in the Person object through the proxy object. What will happen if you access the non-existent properties?

Why does it throw an exception when accessing a non-existent property?

This is because any access to the Person object from the outside world must first pass through the interception layer set by the Proxy, and the interception layer provides a mechanism to filter and rewrite access from the outside world.

// Determine whether the object attribute accessed by the outside world exists in the target object.
if (property in target) {
    return target[property];
} else {
    // If the object property accessed by the outside world does not exist in the target object, an exception is thrown.
    throw new ReferenceError('Property "' + property + '" does not exist.');
}

The if statement is the specific operation of the interception layer, which is to filter and rewrite external access. If not, accessing a non-existent property will return undefined.

set(target, propKey, value, receiver)

It is still a Person object. Now I have a new requirement. When modifying the age attribute, the value cannot exceed 150 and must be an integer.

Added set method in Proxy object.

var proxy = new Proxy(person, {
    set: function (target, property, value) {
          // Print target, property and value to see what is inside.
          console.log("target = ", target);
          console.log("property = ", property);
          console.log("value = ", value);
          if (property === "age") {
                if (!Number.isInteger(value)) {
                  throw new TypeError("The value of age is not an integer!");
                }
                if (value > 150) {
                  throw new RangeError("age cannot be greater than 150!");
                }
          }
    },
});

When I execute proxy.age = 100, the information received by the three parameters of set is shown in the figure below.

The set method is used to intercept the assignment operation of a certain attribute. What will happen if the assignment operation of age does not meet the conditions?

Obviously, an exception will be thrown.

Summarize

Proxy is an interception layer. You give the intercepted object, and the outside world must first pass through the interception layer to access this object, that is, access the instance object of Proxy. Proxy is used to filter and rewrite external access, such as when assigning values, certain conditions must be met.

There are many other methods in the proxy object, such as has, deleteProperty, ownKeys, getOwnPropertyDescriptor, etc., which are used to intercept different situations.

The above is the detailed explanation of the principle of js Proxy. For more information about js Proxy, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Proxy Object in JavaScript
  • JS takes you deep into the world of Proxy
  • Specific use of ES6 Proxy in JavaScript
  • What interesting things can JavaScript Proxy do?
  • Detailed explanation of JavaScript Proxy object

<<:  How to install Graphviz and get started tutorial under Windows

>>:  Detailed steps for installing and configuring MySQL 8.0 on CentOS 7.4 64-bit

Recommend

In-depth analysis of the Tomcat server of Centos 7 system

Table of contents 1. The origin of tomcat 1. Tomc...

Two methods of implementing automatic paging in Vue page printing

This article example shares the specific code of ...

WePY cloud development practice in Linux command query applet

Hello everyone, today I will share with you the W...

Mysql5.7.14 Linux version password forgotten perfect solution

In the /etc/my.conf file, add the following line ...

Quickly solve the problem of slow Tomcat startup, super simple

Today I helped a classmate solve a problem - Tomc...

Analyze Mysql transactions and data consistency processing issues

This article analyzes the consistency processing ...

Detailed explanation of Angular data binding and its implementation

Table of contents Preface What is data binding? T...

How to query data from multiple unrelated tables and paging in Mysql

Mysql multiple unrelated tables query data and pa...

Introduction to scheduled tasks in Linux system

Table of contents 1. Customize plan tasks 2. Sync...

Detailed explanation of nginx reverse proxy webSocket configuration

Recently, I used the webSocket protocol when work...