An article to understand the use of proxies in JavaScript

An article to understand the use of proxies in JavaScript

What is an agent

Definition on MDN: Proxy objects are used to define custom behaviors for basic operations (such as property lookup, assignment, enumeration, function calls, etc.).

The official definition is always so obscure and boring, so what exactly can Proxy do?

1. The concept of agent comes from metaprogramming, which is a kind of program that can read, modify, analyze, and even generate new programs. JS can perform JS metaprogramming through the two objects Proxy and Reflect! !

2.Proxy is a proxy. When it is inconvenient for us to access an object or we are not satisfied with simple access, the proxy can act as a "middleman" to help us better control the operation of the object! !

Basic knowledge of Proxy

grammar:

const handler = {};
let target = {}; //Target object let userProxy = new Proxy(target,handler); //Proxy is implemented successfully! !
userProxy.a = 1;
console.log(target.a);//1
console.log(target == userProxy); //false

target : the target object to be wrapped with Proxy

handle r: An object that usually has functions as attributes, where the functions in each attribute define the behavior of the agent when performing various operations.

OK! Then congratulations, you have mastered the definition of Proxy.

In use, we need to pay more attention to the code of the proxy behavior in the handler, which can help us use Proxy better

Handler object methods

const handler = {
	get(target,prop,receiver){
		console.log('get!');
		return 'a';
	}
}
let target = {name:'tar'};
let userProxy = new Proxy(target,handler);
userProxy.name

Of course, there are many other methods, please refer to MDN: Methods of handler objects

What Proxy can achieve

Tracking property access

When we need to know when an object is accessed or modified.

 let target = {
	name:'ww'
	}
 const handlers = {
    get(tar, prop){
     	console.log('get');
     	return Reflect.get(...arguments); 
     },
     set(tar,prop){
		console.log('set');
		return Reflect.set(...arguments);
	 }
  }
  let userProxy = new Proxy(target, handlers);
  userProxy.name;
  userProxy.name = 'wqw';

Solve the problem of object properties being undefined

let target = {}
  let handlers = {
    get: (target, property) => {
      target[property] = (property in target) ? target[property] : {}
      if (typeof target[property] === 'object') {
        return new Proxy(target[property], handlers)
      }
      return target[property]
    }
  }
  let proxy = new Proxy(target, handlers)
  console.log('z' in proxy.xy) // false (In fact, this step has created an xy attribute for `target`)
  proxy.xyz = 'hello'
  console.log('z' in proxy.xy) // true
  console.log(target.xyz) // hello

We proxy get and perform logical processing inside it. If the value we want to get comes from a non-existent key, we will create the corresponding key in target and then return a proxy object for this key.

This ensures that our value-taking operation will not throw can not get xxx from undefined

However, this will have a small disadvantage, that is, if you really want to determine whether the key exists, you can only use the in operator to determine it, and you cannot directly determine it through get.

References:

MDN-Proxy

JS-Design Patterns

What interesting things can Proxy do?

Metaprogramming

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Reflection and Proxy in Front-end JavaScript
  • JavaScript design pattern learning proxy pattern
  • JavaScript Design Patterns – Proxy Pattern Principles and Usage Example Analysis
  • JavaScript adds event listeners to event delegation in batches. Detailed process
  • In-depth understanding of JavaScript event execution mechanism
  • A brief analysis of event bubbling and event capture in js
  • JavaScript event loop case study
  • Detailed analysis of javascript data proxy and events

<<:  Detailed explanation of how to install mysql5.7.16 from source code in centos7 environment

>>:  Solution to the problem that VMware15 virtual machine bridge mode cannot access the Internet

Recommend

BUG of odd width and height in IE6

As shown in the figure: But when viewed under IE6...

Detailed tutorial on installing mysql 8.0.13 (rpm) on Centos7

yum or rpm? The yum installation method is very c...

How does MySQL implement ACID transactions?

Preface Recently, during an interview, I was aske...

CSS code to achieve 10 modern layouts

Preface I watched web.dev's 2020 three-day li...

MySQL transaction control flow and ACID characteristics

Table of contents 1. ACID Characteristics Transac...

Sample code for implementing radar chart with vue+antv

1. Download Dependency npm install @antv/data-set...

How to display web pages properly in various resolutions and browsers

The key codes are as follows: Copy code The code i...

jQuery implements all shopping cart functions

Table of contents 1. Select All 2. Increase or de...

Docker image analysis tool dive principle analysis

Today I recommend such an open source tool for ex...

Ubuntu 18.04 obtains root permissions and logs in as root user

Written in advance: In the following steps, you n...

Invalid solution when defining multiple class attributes in HTML

In the process of writing HTML, we often define mu...

The current better way to make select list all options when selected/focused

During development, I encountered such a requireme...