let calc = '41+9-(30/2)*2';
let getResult = new Function(`return ${calc}`);
let omg = getResult();
console.log(omg); //20
I really don't understand how it works. Yes, I know that with such a declaration, a function has access only to global variables. As I understand, such a function can turn any string into code. So is it something like "eval"? What is the mechanism of calculating a string and converting it to the result of number type?
If anyone helped me figure this out, I would really appreciate it.
The following code works because we are in the global context already:
const x = 'foo'
const f = new Function(`return x`)
const result = f()
console.log(result) // 'foo'
The following code does not work because we are not in the global context:
(function () {
const x = 'foo'
const f = new Function(`return x`)
const result = f()
console.log(result) // ReferenceError: x is not defined
}())
However, your code is categorically different. String x
is substituted into a template literal... and then the completed string is supplied to the Function
constructor. So the function body is not closing over x
. The function body is literally return 41+9-(30/2)*2
, which is evaluated and the result is returned.
So your code will work, regardless of context:
(function() {
const x = '41+9-(30/2)*2'
const f = new Function(`return ${x}`)
const result = f()
console.log(result) //20
}())