This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge
What is metaprogramming
Let’s start with Meta, it’s been used a lot of times, the first time I saw the word Meta was in an HTML tag, so let’s start with what it means. In fact, Meta is willing to mean post, in fact, the original meaning is a bit advanced and quadratic meaning. But western philosophy over thousands of years has gradually given the affix a whole new meaning, something about something in and of itself. For example, meta-knowledge is knowledge about knowledge itself, meta-data is data about data, meta-language is a language about language, and meta-programming is also derived from this, which is programming about programming.
Metaprogramming definition
Bulk generation of all kinds of code (classes, methods, tests, and so on) reduces programming duplication, and at run time rather than compile time. And metaprogramming is about understanding programs as data and reading that data to produce code at run time.
Lisp, by the way, everyone knows about “code and data,” but that’s what it is. So the definition of simple geololution metaprogramming is to write the code that writes the code, and in Lisp you can use quote to prevent evaluation, and when you need to use it you can use eval.
If you have a deep understanding of Excel, you must be familiar with macros and will often report macro errors. You can execute macros to implement a series of commonly used operations. In programming, too, we use macros in both c++ and rust to pre-define structures or code segments.
In javascript, you can also use eval to execute code strings, but it is not recommended to use this method for metaprogramming.
Starting with ES6, javascript added support for Proxy and Reflect objects, allowing us to wire and define custom behavior for basic language operations (such as attribute lookup, assignment, enumeration, function calls, etc.) to implement meta-level programming of javascript.
Let’s use two examples to show how Proxy and Reflect can change code behavior.
Proxy
const obj = {text:"hello".count:0}
const customObj = new Proxy(obj,{
get:(obj,property) = >{
console.log(obj[property]);
returnobj[property]; }});const textVal = customObj.text
const countVal = customObj.count
Copy the code
hello
0
Copy the code
The code should make sense, changing obj’s GET behavior through the broker, triggering some side effects when calling the customObj property to get the property value.
Reflect
Reflect.get(obj,"text");
Reflect.set(obj,"hello".true);
Reflect.deleteProperty(obj,"count")
console.log(obj)
Copy the code
{ text: 'hello', hello: true }
Copy the code
Let’s take a look at it briefly, and then we’ll expand on it, along with some immediate scenarios that will give us a better understanding of the use of metaprogramming.