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

188
Visualizações
How to remove new Function with Anonymous function in javascript

I am trying to replace eval/new Function with corresponding anonymous function.

Existing Code -

var y = 2
var fn = new Function("return" +y)
console.log(fn)

When i print fn output is

ƒ anonymous(
) {
return2
}

Refactored code which i am writing -

var y = 2
var fn1 = function()  {return y}
console.log(fn1)

But fn1 in this case is

ƒ ()  {return y}

Any pointers how can i get the same output as fn ƒ anonymous() {return2} using my own anonymous function.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can't (at least not without using another version of eval).

You can get the same effect (i.e. not having a mutable y) by using a closure.

var y = 2
var fn1 = function(closure_y) {
  return function() {
    return closure_y;
  }
}(y)
y = 3;
console.log(fn1())

If your code depends on a function stringifying itself in a particular way, then you should probably rewrite the code so it no longer depends on that.

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