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

118
Visualizações
javascript equivalent way of passing variable to anonymous function

In php we can do something like this:

$foo = 1;
$bar = 2;
$fn = function() use ($foo, $bar) {
    return $foo;
};
$foo = 3;
echo $fn(); // gives 1

How to do it in javascript?

I try it like this, but failed:

var foo = 1;
var bar = 2;
var fn = function() { return foo; }.bind(foo,bar);
foo = 3;
console.log(fn()); // gives 3, instead of 1
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

bind is a method to explicitly define the this value and the values passed to the initial arguments of the function.

The arguments that can be passed to a function are defined when the function is created.

var fn = function(foo) { console.log(foo) }

JavaScript doesn't have any features to modify what arguments a function accepts after it has been created.

The scope of a function is also defined when it is created and can't be changed later. If you don't shadow foo with an argument name, then it will read foo from the scope it is defined in.

about 4 years ago · Juan Pablo Isaza Relatório

0

var foo = 1;
var fn = function(foo) { return foo; }.bind({}, foo);

foo = 3;
console.log(fn());

or through context

var foo = 1;
var fn = function() { return this.foo; }.bind({foo});

foo = 3;
console.log(fn());

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