// FYI same thing happens when using a full syntax
const a = () => {
return "hello world"
}
const aString = a.toString()
const b = new Function(aString)
console.log(b()); // undefined
So b is a closure of a and I could not find an option to prevent the wrapping. Anyone knows how to get back the function without a closure?
new Function expects a function body as argument, as stated on mdn:
A string containing the JavaScript statements comprising the function definition.
The parameters of the function are not included: they can be passed as separate arguments.
There are at least two ways to make this work:
eval (but in your edit to the question you write this is not possible for your case -- see alternative):const a = () => {
return "hello world"
}
const aString = a.toString()
const b = eval(aString)
console.log(b()); // "hello world"
Disclaimer: when the stringified function is not fully under your control, it has similar code injection dangers as new Function
new Function, add return and execute it -- this unwraps the wrapper:const a = () => {
return "hello world"
}
const aString = a.toString()
const b = new Function("return " + aString)();
console.log(b()); // "hello world"