Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

What is a Proxy object

As the name implies, the main function of Proxy object is Proxy. Through Proxy, we can intercept Proxy for all operations of an object. Such as object property lookup, property assignment, enumeration, function calls, and so on.

Create a Proxy object

const target = {}
const handler = {}
let proxy = new Proxy(target, handler);
Copy the code

The above code

  • targetIs the target object of our proxy
  • handlerIs also an object that controls the behavior of the target object.

A simple example

Define a simple User object

const user = {
    name: 'the little handsome'.age: 23.email: '[email protected]',}Copy the code

Create a handler object that defines the operation to intercept the target object

const handler = {
    get(target, property) {
        console.log('Read attributes:${property}`);
        returntarget[property]; }}Copy the code

Finally, create the proxy object

const proxyUser = new Proxy(user, handler);
Copy the code

The proxyUser object uses the User object to store data and also has access to all the properties of the User object.

The name and age properties are then printed

console.log(proxyUser.name);
// Output: read attribute: name
// select * from *;
console.log(proxyUser.age);
// Output: read property: age
/ / 23
Copy the code

When we access the properties of the user object through proxyUser, we will pass the get function defined in the proxy handler object, so the console reads the property: XXX.

So if we modify the original User object, the proxyUser object will also change.

user.country = 'china';
console.log(proxyUser.country);
// Output: read property: country
// china
Copy the code

Similarly, if you modify the proxyUser object, the original User object will change.

proxyUser.wechat = 'cmdfas';
console.log(user.wechat);
// Output: cmdfAS
Copy the code

thinking

Now that we know the basics of Proxy objects, what can we do with them?

We all know that Vue3 uses a Proxy Object to replace object.defineProperty () in Vue2. What other cases are there?

That’s it for today, and we’ll pick it up tomorrow, and feel free to comment on your thoughts.

Interested, can pay attention to my public number [small handsome programming notes], follow me every day a little bit of progress