简体   繁体   English

将变量传递给匿名函数的javascript等效方法

[英]javascript equivalent way of passing variable to anonymous function

In php we can do something like this:在 php 中,我们可以这样做:

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

How to do it in javascript?如何在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

bind is a method to explicitly define the this value and the values passed to the initial arguments of the function. bind是一种显式定义this值和传递给函数初始参数的值的方法。

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. JavaScript 没有任何功能可以修改函数在创建后接受的参数。

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.如果您不使用参数名称foo ,那么它将从定义它的范围中读取foo

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM