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

How to implement function currying and decurrying in Javascript

Function currying (black question mark face)? ? ?...

Detailed explanation of virtual DOM and diff algorithm in react

The role of virtual DOM First of all, we need to ...

Solve the mysql user deletion bug

When the author was using MySQL to add a user, he...

Two ways to specify the character set of the html page

1. Two ways to specify the character set of the h...

How to build DockerHub yourself

The Docker Hub we used earlier is provided by Doc...

Example of using JSX to build component Parser development

Table of contents JSX environment construction Se...

Vue3 based on script setup syntax $refs usage

Table of contents 1. Vue2 syntax 2. Use of Vue3 1...

Summary of problems encountered when installing docker on win10 home version

Docker download address: http://get.daocloud.io/#...

Summary of Spring Boot Docker packaging tools

Table of contents Spring Boot Docker spring-boot-...

Several important MySQL variables

There are many MySQL variables, some of which are...

Implementation of CSS heart-shaped loading animation source code

Without further ado, let me show you the code. Th...

JS canvas realizes the functions of drawing board and signature board

This article shares the specific code of JS canva...