SoFunction
Updated on 2025-03-06

Methods for overloading in ES6 for Proxy and Reflect

This article describes the method of overloading (overload) between Proxy and Reflect in ES6. Share it for your reference, as follows:

Proxy and Reflect implement overload (overload)

From a syntax perspective, JavaScript does not support overloading. The reason is very simple. In JS, functions can pass parameters of any type or number, and they can all be obtained by using them in the function. In this way, it is impossible to implement different functions of the parameter list of the same name. Of course, in actual use, you can manually detect the number and type of incoming actual parameters to perform different operations. However, I don't think this can be called overloading.

ES6 brings Proxy and Reflect, which can be reloaded together. Proxy is used to modify the default behavior of certain operations, which is equivalent to "wrapping" the original operations; the methods of the Reflect object correspond to the methods of the Proxy object one by one, which allows the Proxy object to easily call the corresponding Reflect method to complete the default behavior. We can use them like this:

function LogMessage( m ){
   = m;
}
var message = new LogMessage( 1 );
var overload = new Proxy(message , {
  get: function(target, key, receiver){
    (`getting ${key}`);
    return (target , key , receiver);
  },
  set: function(target, key, value, receiver){
    (`setting ${key}`);
    return (target, key, value, receiver);
  }
});
 = 2; //setting m
var s = ; //getting m

Have you seen it? Isn't it very interesting? The newly created Proxy object overload can complete the operation of the target object message. At the same time, you can customize some other operations before the default operation. I think this is more like an overload in Java.

So what are the example methods of Proxy and Reflect?

1.get()
Used to intercept a read operation of a certain attribute.

2.set()
Used to intercept assignment operations of a certain attribute.

3.has()
Some properties can be hidden and not traversed by the in operator.

4.construct()
Used to intercept new commands.

5.deleteProperty()
Used to intercept delete operations.

6.defineProperty()
Used for intercepting operations.

7.enumerate()
Used to intercept for...in loops.

8.getOwnPropertyDescriptor()
Used for intercepting operations.

9.isExtensible()
Used for intercepting operations.

10.preventExtensions()
Used for intercepting operations.

11.setPrototypeOf()
Used for intercepting operations.

Many of the above methods are not very commonly used. If you are interested, you can check the relevant information.

I hope this article will be helpful to everyone's ECMAScript programming.