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

Paragraph layout and line breaks in HTML web pages

The appearance of a web page depends largely on i...

Steps to build a file server using Apache under Linux

1. About the file server In a project, if you wan...

MySQL 8.X installation tutorial under Windows

I had been using MySQL 5.7 before, but because My...

Detailed explanation of MySQL database transaction isolation levels

Database transaction isolation level There are 4 ...

Differentiate between null value and empty character ('') in MySQL

In daily development, database addition, deletion...

Ubuntu 20.04 CUDA & cuDNN Installation Method (Graphical Tutorial)

CUDA installation download cuda Enter the nvidia-...

js to achieve the effect of dragging the slider

This article shares the specific code of how to d...

Solution to the Multiple primary key defined error in MySQL

There are two ways to create a primary key: creat...

Detailed tutorial on installing ElasticSearch 6.x in docker

First, pull the image (or just create a container...

avue-crud implementation example of multi-level complex dynamic header

Table of contents Preface Background data splicin...

VMWare15 installs Mac OS system (graphic tutorial)

Installation Environment WIN10 VMware Workstation...

How to use multi-core CPU to speed up your Linux commands (GNU Parallel)

Have you ever had the need to compute a very larg...