Home > Web Front-end > JS Tutorial > body text

JavaScript's new Function() method you may not know_javascript tips

WBOY
Release: 2016-05-16 16:52:01
Original
1906 people have browsed it

Most of us have used JavaScript. In recent years, the popularity of various JavaScript frameworks has made JavaScript more magical and easier. "Anonymous function? I don't know what it is but it looks similar to what I wrote."
You may not know that you can construct a JavaScript function by passing a string as the body of the function to new Function() . It is not often used in programming, but sometimes it can be very useful.

The following is the basic usage of new Function:

Copy the code The code is as follows:

/ / The last parameter is the body of the function (function body), type is string;
// The previous parameters are the parameters (name) of the function to be constructed
var myFunction = new Function('users', ' salary', 'return users * salary');

Pretty simple, right?

The question is: When is it appropriate to use this method 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 method of function definition is in NodeJS and In the global environment of the browser:

Copy the code The code is as follows:

(function(win) {


// Perform certain operations in the global environment


})(Function('return this')());

If Have you ever used the new Function pattern? Welcome to leave a message and discuss!
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template