Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize overloading overload with Proxy and Reflect in ES6

Shulou Source: shulou.com Published: 2022-05-31 13:32:00 10月13日 Update

This article mainly introduces the ES6 Proxy and Reflect how to achieve overloaded overload related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this ES6 Proxy and Reflect how to achieve overloaded overload article will have a harvest, let's take a look.

Proxy and Reflect to achieve overloading (overload)

Syntactically speaking, JavaScript does not support overloading. The reason is simple: functions in JS can pass any number of parameters of any type, all of which can be obtained by using this.arguments within the function. In this way, it is impossible to achieve different functions with different parameter lists of functions with the same name. Of course, in the actual use process, you can artificially detect the number and type of incoming arguments to carry out different operations. However, I don't think this can be called overloading.

ES6 comes with Proxy and Reflect, which can be overloaded when used together. Proxy is used to modify the default behavior of some operations, which is equivalent to "wrapping" the original operation; the method of the Reflect object corresponds to the method of the Proxy object, which makes it convenient for the Proxy object to call the corresponding Reflect method to complete the default behavior. We can use them like this:

Function LogMessage (m) {this.m = m;} var message = new LogMessage (1); var overload = new Proxy (message, {get: function (target, key, receiver) {console.log (`getting ${key} `); return Reflect.get (target, key, receiver);}, set: function (target, key, value, receiver) {console.log (`setting ${key}`); return Reflect.set (target, key, value, receiver);}); overload.m = 2 / / setting mvar s = overload.m; / / getting m on "how to implement overloaded overload in Proxy and Reflect in ES6" ends here, thank you for reading! I believe you all have a certain understanding of the knowledge of "how to achieve overloaded overload in Proxy and Reflect in ES6". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Different function object method knowledge number content parameter article type behavior primitive one-to-one correspondence this is not value function reason can be passed practical simple operation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB MySQL Shulou Technology Huawei Redmi