1

For my new Project (JavaScript on Node.js) I have to use a Templateproject.

There I found the following Code Snipped. I want to understand what they doing here. For me it makes no sense.

....    
1    lines[lines.length - 1] = lines[lines.length - 1].trim().replace(/};$/, '}');
2        words = lines.join('\n');
3        var resultFunc = new Function('return ' + words + ';');
4
5        return resultFunc();
6    } catch (e) {
....

Why is in Line 4 that "new Function" and what happen here?

Thanks

Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
  • 1
    `new Function` creates a new function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function – Felix Kling Aug 18 '18 at 05:44
  • yes i know. To make my question more clear. Why they fill this String concat in the Function and then call this Function on return statement? When im correct then do this funktion only return words again? –  Aug 18 '18 at 05:47
  • No, the value of `words` is evaluated as JavaScript code. If it retuned just `words`, the code would be `new Function('return words')`. Why they are doing this is impossible to answer without knowing what `words` contains and what the purpose of the function is that this code is contained in. – Felix Kling Aug 18 '18 at 05:55
  • @FelixKling Thank you so much for your fast help. –  Aug 18 '18 at 06:02
  • 1
    For completeness: I have checked the code above this Snippet -> words contains code :-) –  Aug 18 '18 at 07:06

2 Answers2

0

In Javascript, functions are also objects of Function class.

Below is what it means...

Original

//if words = 'some_string'
var resultFunc = new Function('return ' + words + ';');

Equivalent to

//if words = 'somestring'
var resultFunc = function() {
    return 'somestring';
}
Tilak Putta
  • 758
  • 4
  • 18
0

Use new Function() in place of eval().

new Function() is generally used as an alternate for eval() function. Using eval function is considered to be a bad practice because of these reasons. Now, when you pass a string as a parameter to new Function() it would actually create a function with the code in that string as the body of the function. Therefore you can think of line var resultFunc = new Function('return ' + words + ';'); as:

var words = "someValue";
var resultFunc = function () {
  return "someValue";
}
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54