Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda