Now I study Js on the textbook https://learn.javascript.ru .

Question by function:

var sum = new Function('a,b', ' return a+b; '); var result = sum(1, 2); alert( result ); // 3 

That is, the function is created by calling new Function (params, code):

params
Function parameters separated by commas as strings.
code
Function code as a string.
Thus, it is possible to construct a function whose code is unknown at the time of writing the program, but a string with it is generated or loaded dynamically during its execution.

I did not understand how the function code is unknown at the time of writing the program, if the second parameter indicates ' return a+b; ' ' return a+b; ' ? Or do you mean that you can leave this parameter empty, ''?

  • function body line can be dynamically composed - Grundy
  • @Grundy, can you give me an example? - ra.chobanyan

1 answer 1

Since in this case, the normal string is transferred as the function body, it can be collected as you like before, because of variables whose value is unknown at the time of writing.

For example:

 function calc(x, expr) { var func = new Function('x', `return ${expr}`); console.log(func(x)); } 
 <input type="text" id="expr" value="x*x" /> <br/> <input type="text" id="x" value="2" /> <br/> <button onclick="calc(x.value, expr.value)">Calc</button>