[英]Passing a function with parameters as a parameter?
Is it possible to pass a javascript function with parameters as a parameter?是否可以将带有参数的 javascript function 作为参数传递?
Example:例子:
$(edit_link).click( changeViewMode( myvar ) );
Use a "closure":使用“闭包”:
$(edit_link).click(function(){ return changeViewMode(myvar); });
This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.这将创建一个匿名临时函数包装器,它知道参数并将其传递给实际的回调实现。
Use Function.prototype.bind()
.使用Function.prototype.bind()
。 Quoting MDN:引用 MDN:
The
bind()
method creates a new function that, when called, has itsthis
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.bind()
方法创建一个新函数,在调用this
函数时,将其this
关键字设置为提供的值,并在调用新函数时在任何提供的参数之前提供给定的参数序列。
It is supported by all major browsers, including IE9+.所有主流浏览器都支持它,包括 IE9+。
Your code should look like this:您的代码应如下所示:
$(edit_link).click(changeViewMode.bind(null, myvar));
Side note: I assume you are in global context, ie this
variable is window
;旁注:我假设你在全局上下文中,即this
变量是window
; otherwise use this
instead of null
.否则使用this
而不是null
。
No, but you can pass one without parameters, and do this:不,但您可以不带参数传递一个,然后执行以下操作:
$(edit_link).click(
function() { changeViewMode(myvar); }
);
So you're passing an anonymous function with no parameters, that function then calls your parameterized function with the variable in the closure所以你传递了一个没有参数的匿名函数,然后该函数使用闭包中的变量调用你的参数化函数
或者,如果您使用的是 es6,您应该能够使用箭头函数
$(edit_link).click(() => changeViewMode(myvar));
是的,像这样:
$(edit_link).click(function() { changeViewMode(myvar) });
This is an example following Ferdinand Beyer's approach:这是遵循 Ferdinand Beyer 方法的示例:
function function1()
{
function2(function () { function3("parameter value"); });
}
function function2(functionToBindOnClick)
{
$(".myButton").click(functionToBindOnClick);
}
function function3(message) { alert(message); }
In this example the "parameter value" is passed from function1 to function3 through function2 using a function wrap.在此示例中,“参数值”使用函数包装从函数 1 通过函数 2 传递到函数 3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.