An article to understand proxies and their use in JavaScript

  • 2021-11-13 00:50:48
  • OfStack

Directory What is the basic knowledge of proxy Proxy handler object method Proxy can implement resources: summary

What is an agent

Definition on MDN: Proxy (that is, proxy) objects are used to define custom behaviors for basic operations (such as property lookups, assignments, enumerations, function calls, and so on).

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

1. The concept of proxy comes from metaprogramming, where you can write a program that can read, modify, parse, and even generate new programs. And JS can be through Proxy and Reflect these two objects for js meta-programming! !

2. Proxy is a proxy. When we are inconvenient to access an object or 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

Syntax:


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

target: Target object to be wrapped with Proxy

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

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

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

handler Object Method


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 other methods. Please refer to the methods of MDN: handler objects

What Proxy can achieve

Trace property access

When we need to know when objects are accessed and 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 that the object attribute is 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.x.y) // false ( In fact, this 1 Step has been targeted for `target` Created the 1 A x.y Properties of )
  proxy.x.y.z = 'hello'
  console.log('z' in proxy.x.y) // true
  console.log(target.x.y.z)     // hello

We proxy get and logically process it. If the value of get comes from a non-existent key, we will create a corresponding key in target, and then return a proxy object for this key.

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

However, this has a small disadvantage, that is, if you really want to judge whether this key exists, you can only judge it by in operator, not directly by get.

References:

MDN-Proxy

JS-Design Pattern

What interesting things can Proxy do

Metaprogramming

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: