In the previous blog post, I introduced a method that can make JavaScript have some programming capabilities similar to Lambda expressions . However, since it needs to be compatible with JavaScript's syntax check, it can be used in many situations. limited.
However, some more attentive friends may have discovered that I used a few tricks in that (pseudo) Lambda module. Now I will introduce these tips:
1. Use new Function to perform syntax checking.
Students who try to write frameworks must have a deep feeling about this: sometimes the code generated through the code may produce grammatical errors due to technical mistakes, resulting in abnormal interruption during operation; Sometimes it is necessary to accept user input, but users may write incorrect statements or expressions intentionally or unintentionally.
Some students deliberately write (or use ready-made) complex syntax checking processes to solve this problem - but writing code to analyze code syntax is an extremely painful thing, and once the problem is discovered, it is also very difficult to adjust. inconvenient.
In fact, there is a simpler solution to this problem, which is to use the script engine's own syntax check, such as eval or new Function - of course, this eval cannot be used indiscriminately. If eval is used inappropriately, the entire program will be corrupted. There is a problem; but new Function is not such a big problem - although the function constructed by new Function works directly in the global scope under any circumstances, if it is just a syntax check, it will not cause scope problems. Unexpected result, as long as you don't actually call the new function constructed through it directly.
2. Add "0," in front of the parameters accepted by eval.
Actually, this is due to a BUG in IE.
For some magical reason, if you want to dynamically construct a function in IE by calling eval, if you just add parentheses around the expression of the function - for example: