These two apis are rarely used in actual business scenarios, which may need to be explored. It seems that every API has some other API that can be simulated and used to intercept, execute, and return results.

Proxy

On the face of it, this should make sense, just like Nginx, to request a proxy. Let’s look at a very small example:

let handler = {
    get: function(target. name) {
        return name in target ? target[name] : 37;
    }
};

let p = new Proxy({}, handler);

p.a = 1;
p.b = undefined;

console.log(p.a. p.b); 
// 1, undefined

console.log('c' in p. p.c); 
Copy the code

Create a custom behavior using the New Proxy, and the handler serves as the catcher to capture the behavior of the object operation. In this way, it is very much like object.defineProperty to create a get and set method. Since b already exists, undefined is returned. When we print c, p.c will return 37.

If you’re interested, read Proxy

Reflect

Reflect is also very similar to a Proxy in that it provides methods that intercept JavaScript. Unlike proxies, Reflect provides static methods that do not use the new operator.

Get a property:

let obj = {a:1}

console.log(Reflect.get(obj.'a'))
Copy the code

Set a property:

let obj = {};
Reflect.set(obj. "prop". "value"); // true
obj.prop; // "value"
Copy the code

To call a function:

Reflect.apply(Math.floor. undefined. [1.75]); 
Copy the code

This differs from function apply only in that the first argument must be the function to call, and the last two arguments are the same as function apply.

For more on this, read: Reflect

To be honest, I am a little confused about the application scenarios of these two apis, and I may have to use them frequently to compare them to see the difference between methods that should have the same functionality.

For more exciting content, please follow my wechat official account: search Fed-Talk