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

js implements the algorithm for specifying the order and amount of red envelopes

This article shares the specific code of js to im...

How to implement scheduled backup of CentOS MySQL database

The following script is used for scheduled backup...

React realizes the whole process of page watermark effect

Table of contents Preface 1. Usage examples 2. Im...

CSS Naming: BEM, scoped CSS, CSS modules and CSS-in-JS explained

The scope of css is global. As the project gets b...

A comprehensive analysis of what Nginx can do

Preface This article only focuses on what Nginx c...

MySQL slow_log table cannot be modified to innodb engine detailed explanation

background Getting the slow query log from mysql....

Examples of using the Li tag in HTML

I hope to align the title on the left and the dat...

Detailed explanation of MySQL date string timestamp conversion

The conversion between time, string and timestamp...

Detailed explanation of Docker Compose deployment and basic usage

1. Docker Compose Overview Compose is a tool for ...

Tomcat CentOS installation process diagram

Tomcat CentOS Installation This installation tuto...

What to do if you forget the initial password of MySQL on MAC

The method to solve the problem of forgetting the...

Detailed explanation of the application of the four states of hyperconnection

Although you think it may be a browser problem, i...

About MariaDB database in Linux

Table of contents About MariaDB database in Linux...

Css3 realizes seamless scrolling and anti-shake

question The seamless scrolling of pictures and t...