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

94
Visualizações
How to set a local variable from new function in JavaScript

I have a function with a variable. I need to run code from a string to modify that variable. How would I set a local variable from new Function() or something similar?

function alertNumber() {
  var number = 5;
  var f = new Function("number = 4");
  f();
  console.log("local " + number); //should alert 4
  console.log("window " + window.number); //instead of the local variable, it sets the property to the window
}
alertNumber();

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

0

With new Function, it's not possible.

However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in the global scope only.

You would need

function alertNumber() {
  var number = 5;
  eval("number = 4");
  console.log("local " + number); //should alert 4
}
alertNumber();

(though having to do this in the first place is quite suspicious - if it were me, I'd consider hard if there were really no alternatives first)

about 4 years ago · Juan Pablo Isaza Relatório

0

Just create a new function that modifies the number and then returns the result of the modified number:

// This should fix your problem

function modifyNumber(number) {
  return number = 4
}

function alertNumber() {
  var number = 5
  number = modifyNumber(number)
  console.log("local " + number) // outputs "local 4"
}
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