You may not know the JavaScript new Function () method _javascript Tips

Source: Internet
Author: User
Tags function definition

Most of us have used JavaScript, and in recent years the popularity of JavaScript frameworks has made JavaScript more magical and easy. "Anonymous (anonymous) function?" I don't know what it is, but it seems to be the same as what I wrote. ”
You may not know that you can pass the new function () a string as the body of the function to construct a JavaScript function. It's not often used in programming, but sometimes it should be useful.

The following is the basic usage of the new Function:

Copy Code code as follows:

The last parameter is the body (function) of the function, and the type is string;
The previous arguments are the arguments for the constructed function (first name)
var myfunction = new Function (' users ', ' salary ', ' return users * salary ');

It's very simple, isn't it?

The question is: when is it appropriate to use this approach, instead of using the traditional function declaration functions Myfnname () and/or anonymous function definitions? Andrea Giammarchi that the most appropriate scenario for using this function definition is in the global context of Nodejs and browsers:

Copy Code code as follows:

(function (Win) {


Performing certain actions in the global environment


}) (Function (' Return this ') ());

If you have ever used the new function mode, please comment and discuss!

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.