New Function
requires a function body as input, which is clearly explained on the mdn website:
The function definition should be a string containing JavaScript statements.
It's important to note that the parameters for the function are not included in this string and need to be passed separately.
There are multiple approaches to achieving this functionality:
- You can utilize
eval
, but if that's not an option (as mentioned in your question), consider the alternative approach:
const a = () => {
return "hello world"
}
const aString = a.toString()
const b = eval(aString)
console.log(b()); // "hello world"
Please be cautious: similar to using New Function
, when dealing with a stringified function that isn't entirely controlled by you, there may be risks of code injection.
- If you prefer to stick to using
New Function
, ensure you include a return
statement and then execute it to unwrap the wrapper:
const a = () => {
return "hello world"
}
const aString = a.toString()
const b = new Function("return " + aString)();
console.log(b()); // "hello world"