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

238
Visualizações
How can I create a function which treats a passed parameter as a literal?

I am sure that this has been asked and answered before, but I can't seem to find the right terminology to find an answer. I need to dynamically create a series of functions for later use which use certain values defined by parameters upon creation. For example:

var i = "bar";

var addBar = function(x) {
    // needs to always return x + " " + "bar"
  return x + " " + i;
}

i = "baz";

var addBaz = function(x) {
    // needs to always return x + " " + "baz"
  return x + " " + i;
}

alert(addBar("foo")); // returns "foo baz" because i = "baz"

Is there a way I can pass i to these functions so that the original value is used, and not the reference to the variable? Thank you!

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

0

You would have to do something that stores the variable. Making a function that returns a function is one way to do it.

var i = "bar";

var addBar = (function (i) { 
  return function(x) {
    return x + " " + i;
  }
}(i));

i = "baz";

var addBaz = (function (i) { 
  return function(x) {
    return x + " " + i;
  }
}(i));

console.log(addBar("foo")); 
console.log(addBaz("foo")); 

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