Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
Convert function to string and back in javascript

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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"

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda