2

// 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?

6
  • (() => { return "hello world"; }).toString() is "() => { return \"hello world\"; }". new Function creates a function with the given body, i.e. (function(){ () => { return "hello world"; } }). What you’re looking for is eval. Commented Sep 15, 2021 at 20:38
  • @SebastianSimon unfortunately CSP prevents eval code from running and that's beyond my control Commented Sep 15, 2021 at 20:40
  • Whatever prevents eval should also prevent new Function, then. If new Function “works”, then the obvious alternative would be new Function(`return ${aString};`)(). Commented Sep 15, 2021 at 20:42
  • eval() works in trincot's answer. Commented Sep 15, 2021 at 20:44
  • I hope this question is just for curiosity’s sake. If not, what is the actual problem that you think requires new Function to solve? There is definitely a better way. Commented Sep 15, 2021 at 20:45

1 Answer 1

2

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:

  1. 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

  1. 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"

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.