Introduction to DSL metaprogramming in JavaScript
This article mainly introduces DSL meta-programming in JavaScript. This article describes JavaScript meta-programming, JavaScript eval, JavaScript new Function (), and other content. For more information, see
When I looked at the JavaScript Template source code, I found a very interesting usage to generate a function. do I think this is not just metaprogramming?
JavaScript metaprogramming
The Code is as follows:
Metaprogramming refers to the compilation of a certain type of computer program. Such computer programs write or manipulate other programs (or themselves) as their data, or complete part of the work that should have been completed during compilation at runtime.
JavaScript eval
The Code is as follows:
The eval () function computes a string and executes the JavaScript code.
You can use the following methods:
The Code is as follows:
Eval ("x = 10; y = 20; document. write (x * y )")
Of course, this is only used to execute a function, but it is cost-effective and error-prone.
Copy the Code as follows:
Eval functions should be avoided as much as possible.
So the better way is to use New Function ()
A major difference between using New Function () and eval () Is that eval is not just a Function,
The Code is as follows:
Eval () calculates a string as a JavaScript expression within the current execution range and can access local variables. New Function () parsing stores the JavaScript code that can be called after a string is converted into a Function object. Because the code runs in a separate range, local variables cannot be accessed.
That is to say, eval () will interfere with the scope of the current function ..
JavaScript new Function ()
The Function constructor creates a new Function object. in JavaScript, each function is actually a Function object. the Function object generated by the Function constructor is parsed when the Function is created. This is more inefficient than using function declaration and calling in your code, because the function declared using function statements is parsed together with other statements.
Compared with New Function (), it will be relatively inefficient, and this is what we can predict in the current situation.
A simple example is as follows:
The Code is as follows:
Var add = new Function (['x', 'y'], 'Return x + y ');
New Function () parses the string into a Function .. Then we can use apply to execute
The Code is as follows:
Function. apply (null, args)
This is what I see in JavaScript Template:
The Code is as follows:
New Function (
Tmpl. arg + ', tmpl ',
"Var _ e = tmpl. encode" + tmpl. helper + ", _ s = '" +
Str. replace (tmpl. regexp, tmpl. func) +
"'; Return _ s ;"
);
Of course we have other methods.