Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda