The new Function () method of JavaScript that you may not know

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.