[英]JS - how to pass function as parameter (with parameters) without invoking it
I have this method: 我有这种方法:
myFunction: function(a,b,c) {
...
}
Now, I want to pass it as parameter to another method so it can be executed inside that method: 现在,我想将其作为参数传递给另一个方法,以便可以在该方法内部执行:
...
var a = "bla";
var b = "ble";
var c = "bli";
someFunction(myFunction(a,b,c),true,"test");
And then inside someFunction I would like to call myFunction like: 然后在someFunction中,我想像这样调用myFunction:
someFunction: function(func,bool,str){
func();
}
Is that possible? 那可能吗?
Thanks 谢谢
Yes, but you have to create a function that makes the function call, ie bind (aka "curry") the function reference with the parameters: 是的,但是您必须创建一个进行函数调用的函数,即将函数引用与参数绑定 (也称为“ curry”):
someFunction(myFunction.bind(this, a, b, c), true, "test");
Some older browsers (eg IE 8) doesn't support the bind
method, but you can do basically the same with a function expression: 一些较旧的浏览器(例如IE 8)不支持bind
方法,但是您可以使用函数表达式执行基本相同的操作:
someFunction(function() { myFunction(a, b, c); }, true, "test");
If you are using jQuery there is a $.proxy
method that takes care of making it browser independent: 如果您使用的是jQuery,则可以使用$.proxy
方法来使其独立于浏览器:
someFunction($.proxy(myFunction, this, a, b, c), true, "test");
Yes, this is possible in JavaScript. 是的,这在JavaScript中是可能的。
someFunction(function () {
myFunction(a,b,c);
}, true, "test");
You can even do: 您甚至可以:
var myFunc = function () {
myFunction(a,b,c);
};
someFunction(myFunc, true, "test");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.