Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!