When looking at the source code of JavaScript Template, I found that there is an interesting usage to generate functions. Isn’t this metaprogramming?
JavaScript metaprogramming
The code copy is as follows:
Metaprogramming refers to the writing of a certain type of computer program that writes or manipulates other programs (or itself) as their data, or completes some of the work that should have been completed at compile time at runtime.
JavaScript eval
The code copy is as follows:
The eval() function calculates a string and executes the JavaScript code in it.
There may be the following usage:
The code copy is as follows:
eval("x=10;y=20;document.write(x*y)")
Of course, this is just used to execute a certain function, but this product is cheaper and easy to make mistakes.
The code copy is as follows:
The eval function should be avoided as much as possible.
So a better way is to use New Function()
A big difference between using New Function() and eval() is that eval is not just a function.
The code copy is as follows:
eval() calculates a string as a JavaScript expression within the current execution scope, allowing access to local variables. New Function() parses JavaScript code stored in a string converted into a function object and can then be called. 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 is actually a Function object. Function objects generated using the Function constructor are parsed when the function is created. This is less efficient than using function declarations and calling them in your code, because functions declared using function statements are parsed with other statements.
New Function() is inefficient in comparison, which is what we can predict under the current circumstances.
A simple example is as follows:
The code copy is as follows:
var add = new Function(['x', 'y'], 'return x + y');
new Function() parses the string into a function. . Then we can execute it by applying
The code copy is as follows:
Function.apply(null, args)
And this is what I saw in JavaScript Template:
The code copy 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 ways.