Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize overloading of Proxy and Reflect in ES6

Shulou Source: shulou.com Published: 2022-06-01 02:05:13 10月04日 Update

This article mainly introduces the relevant knowledge of "how to achieve overloading of Proxy and Reflect in ES6". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "how to achieve overloading of Proxy and Reflect in ES6" can help you solve the problem.

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 overload Proxy and Reflect in ES6", thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Different methods functions objects knowledge number parameters actual type industry behavior process original practical one-to-one correspondence this is not content function reason can be obtained through Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Apple Shulou Information Docker Microsoft