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:
- You could use
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
- To only use
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"
(() => { return "hello world"; }).toString()is"() => { return \"hello world\"; }".new Functioncreates a function with the given body, i.e.(function(){ () => { return "hello world"; } }). What you’re looking for iseval.evalshould also preventnew Function, then. Ifnew Function“works”, then the obvious alternative would benew Function(`return ${aString};`)().eval()works in trincot's answer.new Functionto solve? There is definitely a better way.