lytabu
lytabu

Reputation: 65

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

Upvotes: 1

Views: 47

Answers (2)

MelKam
MelKam

Reputation: 58

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());

Upvotes: 0

Quentin
Quentin

Reputation: 944203

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.

Upvotes: 2

Related Questions