Click on the above Programmer Growth North, pay attention to the public account

Reply 1, join the advanced node communication group

English | https://javascript.plainenglish.io/in-depth-js-new-function-syntax-b1957c5dab69

JavaScript technology has been in constant development, if you are a front-end developer or JavaScript development engineer, then, today’s knowledge point, you need to seriously understand, it is “new Function”.

1. Grammar

The syntax is as follows:

The last argument must be the function body, and the remaining parameters are passed to the function body.

For example:

When we usually develop JavaScript or Node.js, there is no reason to use the new Function constructor, because there is no need to use the function or the () => {} arrow function directly.

Does this mean that the new Function syntax is a chicken rib?

Don’t think so! Because it’s definitely not what you think!

 The new Function syntax has a particularly powerful feature that makes it an irreplaceable role in JavaScript.

What are the features? That is, the data format of the function body is a string, which is really incredible!

An irreplaceable role

Here are a few examples to illustrate the subtleties of the new Function syntax.

01). Invalid JSON object string legalization

For example, there is the following string:

The strings do not conform to the JSON format (the key value requires double quotation marks), and parsing with JSON.parse() will report an error.

So, is there any way to convert this string object into a parsable JSON?

Many people will think of regular matching and then substitution, or using slag attributes such as eval for processing.

No need to bother, new Function is online, it’s perfect!

The JS code looks like this:

Using the return syntax, you can easily convert arbitrary strings to other JavaScript data types.

02). Template string as template

For example, Vue, React, etc. now have their own template syntax, such as {} syntax.

If we want to use ES6’s own syntax directly as a template language, we must use the capabilities of new functions, such as the following HTML:

We can extend the string and define a string method called interpolate to convert the ES6 syntax string to executable ES6 code:

At this point, as long as there is the corresponding data, we can