Most of us have used JavaScript. In recent years, JavaScript has become more magical and easy with the popularity of various JavaScript frameworks. "Anonymous (Anonymous) function? I don't know what it is, but it looks similar to what I wrote ."
You may not know that you can pass a new Function () string as the Function body to construct a JavaScript Function. Programming is not often used, but sometimes it should be very useful.
The basic usage of new Function is as follows:
Copy codeThe Code is as follows:
// The last parameter is the function body, which is of the string type;
// The preceding parameters are the parameters (names) of the constructed functions)
Var myFunction = new Function ('users', 'salary ', 'Return users * salary ');
Very simple, right?
Q: When is this method suitable, instead of using the traditional function declaration function myFnName () and/or anonymous function definition? Andrea Giammarchi believes that the most suitable scenario for using this function definition method is in the global environment of NodeJS and browsers:
Copy codeThe Code is as follows:
(Function (win ){
// Perform some operations in the global environment
}) (Function ('Return this ')());
If you have used the new Function mode, please leave a message and discuss it!