1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.