When I was looking at the JavaScript Template source code, I found a very interesting usage for generating functions. I thought, isn’t this metaprogramming?
JavaScript Metaprogramming
Metaprogramming refers to the writing of certain types of computer programs that write or manipulate other programs (or themselves) as their data, or complete some work at runtime that should be completed at compile time.
JavaScript eval
The eval() function evaluates a string and executes the JavaScript code within it.
It can be used as follows:
eval("x=10;y=20;document.write(x*y)")
Of course, this is only used to execute a certain function, but this product is very cost-effective and error-prone.
The eval function should be avoided whenever possible.
So a better way is to use New Function()
The big difference between using New Function() and eval() is that eval is not just a function,
eval() evaluates a string as a JavaScript expression within the current execution scope and can access local variables. New Function() parses a string stored in it into a function object that can then be called by JavaScript code. Because the code runs in a separate scope, local variables cannot be accessed.
In other words, 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 (function) is actually a Function object. The Function object generated using the Function constructor is parsed when the function is created. This is less efficient than if you declare a function and call it in your code, because functions declared using function statements are parsed along with other statements.
New Function() will be less efficient in comparison, and this is what we can predict under the current situation.
A simple example looks like this:
var add = new Function(['x', 'y'], 'return x y');
new Function() will parse the string into a function. . Then we can execute it through apply
Function.apply(null, args)
And this is what I see in the JavaScript Template:
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.